{"version":3,"file":"static/js/main.500ff735.js","sources":["../node_modules/@emotion/sheet/dist/emotion-sheet.esm.js","../node_modules/stylis/src/Utility.js","../node_modules/stylis/src/Tokenizer.js","../node_modules/stylis/src/Enum.js","../node_modules/stylis/src/Serializer.js","../node_modules/stylis/src/Parser.js","../node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js","../node_modules/stylis/src/Middleware.js","../node_modules/@emotion/memoize/dist/emotion-memoize.esm.js","../node_modules/@emotion/react/dist/emotion-element-5486c51c.browser.esm.js","../node_modules/@emotion/react/dist/emotion-react.browser.esm.js","../node_modules/@emotion/serialize/node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../node_modules/@emotion/serialize/dist/emotion-serialize.esm.js","../node_modules/@emotion/hash/dist/emotion-hash.esm.js","../node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js","../node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js","../node_modules/@mui/styled-engine/GlobalStyles/GlobalStyles.js","../node_modules/@emotion/styled/node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js","../node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js","../node_modules/@emotion/styled/dist/emotion-styled.browser.esm.js","../node_modules/@mui/styled-engine/StyledEngineProvider/StyledEngineProvider.js","../node_modules/@mui/styled-engine/index.js","../node_modules/@mui/system/colorManipulator.js","../node_modules/@mui/system/createStyled.js","../node_modules/@mui/system/esm/breakpoints.js","../node_modules/@mui/system/esm/createTheme/applyStyles.js","../node_modules/@mui/system/esm/createTheme/createBreakpoints.js","../node_modules/@mui/system/esm/createTheme/shape.js","../node_modules/@mui/system/esm/createTheme/createTheme.js","../node_modules/@mui/system/esm/createTheme/createSpacing.js","../node_modules/@mui/system/esm/merge.js","../node_modules/@mui/system/esm/spacing.js","../node_modules/@mui/system/esm/memoize.js","../node_modules/@mui/system/esm/style.js","../node_modules/@mui/system/esm/compose.js","../node_modules/@mui/system/esm/borders.js","../node_modules/@mui/system/esm/cssGrid.js","../node_modules/@mui/system/esm/palette.js","../node_modules/@mui/system/esm/sizing.js","../node_modules/@mui/system/esm/styleFunctionSx/defaultSxConfig.js","../node_modules/@mui/system/esm/styleFunctionSx/extendSxProp.js","../node_modules/@mui/system/esm/styleFunctionSx/styleFunctionSx.js","../node_modules/@mui/system/useThemeWithoutDefault.js","../node_modules/@mui/utils/esm/capitalize/capitalize.js","../node_modules/@mui/utils/esm/clamp/clamp.js","../node_modules/@mui/utils/esm/deepmerge/deepmerge.js","../node_modules/@mui/utils/esm/formatMuiErrorMessage/formatMuiErrorMessage.js","../node_modules/@mui/utils/esm/getDisplayName/getDisplayName.js","../node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/base-x/src/index.js","../node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/node_modules/bs58/index.js","../../src/Layout.ts","../node_modules/@solana/wallet-adapter-base/node_modules/eventemitter3/index.js","../node_modules/@stablelib/binary/binary.ts","../node_modules/@stablelib/chacha/chacha.ts","../node_modules/@stablelib/chacha20poly1305/chacha20poly1305.ts","../node_modules/@stablelib/constant-time/constant-time.ts","../node_modules/@stablelib/ed25519/ed25519.ts","../node_modules/@stablelib/hash/hash.ts","../node_modules/@stablelib/hkdf/hkdf.ts","../node_modules/@stablelib/hmac/hmac.ts","../node_modules/@stablelib/int/int.ts","../node_modules/@stablelib/poly1305/poly1305.ts","../node_modules/@stablelib/random/random.ts","../node_modules/@stablelib/random/source/browser.ts","../node_modules/@stablelib/random/source/node.ts","../node_modules/@stablelib/random/source/system.ts","../node_modules/@stablelib/sha256/sha256.ts","../node_modules/@stablelib/sha512/sha512.ts","../node_modules/@stablelib/wipe/wipe.ts","../node_modules/@stablelib/x25519/x25519.ts","../../crypto.ts","../../env.ts","../../index.ts","../node_modules/@walletconnect/environment/node_modules/tslib/tslib.es6.js","../node_modules/node_modules/lodash/lodash.js","../node_modules/@walletconnect/universal-provider/src/constants/values.ts","../node_modules/@walletconnect/universal-provider/src/constants/events.ts","../../events.ts","../node_modules/@walletconnect/jsonrpc-http-connection/node_modules/cross-fetch/dist/browser-ponyfill.js","../../constants.ts","../../error.ts","../../format.ts","../node_modules/@walletconnect/jsonrpc-types/src/misc.ts","../../url.ts","../../validators.ts","../node_modules/@walletconnect/jsonrpc-ws-connection/node_modules/ws/browser.js","../node_modules/destr/dist/index.mjs","../node_modules/unstorage/dist/shared/unstorage.8581f561.mjs","../node_modules/unstorage/dist/index.mjs","../node_modules/idb-keyval/dist/index.js","../node_modules/@walletconnect/relay-api/src/misc.ts","../node_modules/@walletconnect/relay-auth/node_modules/uint8arrays/esm/src/util/as-uint8array.js","../node_modules/@walletconnect/relay-auth/node_modules/uint8arrays/esm/src/alloc.js","../node_modules/@walletconnect/relay-auth/node_modules/uint8arrays/esm/src/util/bases.js","../node_modules/@walletconnect/relay-auth/node_modules/uint8arrays/esm/src/to-string.js","../node_modules/@walletconnect/relay-auth/node_modules/uint8arrays/esm/src/from-string.js","../../utils.ts","../node_modules/@walletconnect/relay-auth/node_modules/uint8arrays/esm/src/concat.js","../../api.ts","../../../../src/constants/index.ts","../../../../src/constants/misc.ts","../../../../src/constants/time.ts","../../../../src/types/index.ts","../../../../src/types/watch.ts","../../../../src/utils/convert.ts","../../../../src/utils/delay.ts","../../../../src/utils/index.ts","../../watch.ts","../node_modules/@walletconnect/time/node_modules/tslib/tslib.es6.js","../node_modules/@walletconnect/utils/src/caip.ts","../node_modules/@walletconnect/utils/src/misc.ts","../node_modules/base-x/src/index.js","../node_modules/base64-js/index.js","../node_modules/bigint-buffer/dist/browser.js","../node_modules/bn.js/lib/bn.js","../node_modules/borsh/lib/index.js","../node_modules/bs58/index.js","../node_modules/buffer/index.js","../node_modules/dayjs/dayjs.min.js","../node_modules/dayjs/locale/en.js","../node_modules/dayjs/plugin/relativeTime.js","../node_modules/dayjs/plugin/updateLocale.js","../node_modules/decode-uri-component/index.js","../node_modules/detect-browser/es/index.js","../node_modules/dijkstrajs/dijkstra.js","../node_modules/encode-utf8/index.js","../node_modules/eventemitter3/index.js","../node_modules/events/events.js","../node_modules/filter-obj/index.js","../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js","../node_modules/hoist-non-react-statics/node_modules/react-is/index.js","../node_modules/ieee754/index.js","../node_modules/jayson/lib/client/browser/index.js","../node_modules/jayson/lib/generateRequest.js","../node_modules/lodash.isequal/index.js","../node_modules/object-assign/index.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/index.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/qrcode/lib/browser.js","../node_modules/qrcode/lib/can-promise.js","../node_modules/qrcode/lib/core/alignment-pattern.js","../node_modules/qrcode/lib/core/alphanumeric-data.js","../node_modules/qrcode/lib/core/bit-buffer.js","../node_modules/qrcode/lib/core/bit-matrix.js","../node_modules/qrcode/lib/core/byte-data.js","../node_modules/qrcode/lib/core/error-correction-code.js","../node_modules/qrcode/lib/core/error-correction-level.js","../node_modules/qrcode/lib/core/finder-pattern.js","../node_modules/qrcode/lib/core/format-info.js","../node_modules/qrcode/lib/core/galois-field.js","../node_modules/qrcode/lib/core/kanji-data.js","../node_modules/qrcode/lib/core/mask-pattern.js","../node_modules/qrcode/lib/core/mode.js","../node_modules/qrcode/lib/core/numeric-data.js","../node_modules/qrcode/lib/core/polynomial.js","../node_modules/qrcode/lib/core/qrcode.js","../node_modules/qrcode/lib/core/reed-solomon-encoder.js","../node_modules/qrcode/lib/core/regex.js","../node_modules/qrcode/lib/core/segments.js","../node_modules/qrcode/lib/core/utils.js","../node_modules/qrcode/lib/core/version-check.js","../node_modules/qrcode/lib/core/version.js","../node_modules/qrcode/lib/renderer/canvas.js","../node_modules/qrcode/lib/renderer/svg-tag.js","../node_modules/qrcode/lib/renderer/utils.js","../node_modules/query-string/index.js","../node_modules/quick-format-unescaped/index.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/client.js","../node_modules/react-dom/index.js","../node_modules/react-fast-compare/index.js","../node_modules/react-is/cjs/react-is.production.min.js","../node_modules/react-is/index.js","../node_modules/react-side-effect/lib/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/jsx-runtime.js","../node_modules/safe-buffer/index.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/shallowequal/index.js","../node_modules/split-on-first/index.js","../node_modules/strict-uri-encode/index.js","../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js","../node_modules/use-sync-external-store/shim/index.js","../node_modules/use-sync-external-store/shim/with-selector.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/regex.js","../node_modules/uuid/dist/esm-browser/validate.js","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/v4.js","../node_modules/void-elements/index.js","../node_modules/@lifi/widget/node_modules/zustand/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../node_modules/@lifi/widget/node_modules/zustand/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js","../node_modules/@lifi/widget/node_modules/zustand/node_modules/use-sync-external-store/shim/index.js","../node_modules/@lifi/widget/node_modules/zustand/node_modules/use-sync-external-store/shim/with-selector.js","../node_modules/pino/browser.js","../node_modules/@babel/runtime/helpers/extends.js","../node_modules/@babel/runtime/helpers/interopRequireDefault.js","../node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js","../node_modules/@lifi/sdk/node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/contract.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/contracts.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/call.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/errors/getCallError.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/abis.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/solidity.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/unit.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/abi.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/address.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/version.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/base.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/chain.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/formatAbiItemWithArgs.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/contract.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/data.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/encoding.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/node.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/request.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/stateOverride.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/transaction.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/utils.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/encoding/fromBytes.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/decodeAbiParameters.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/decodeErrorResult.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/formatAbiItem.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/toEventSelector.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/address/getAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/address/isAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/cursor.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/cursor.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/data/concat.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/data/isHex.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/data/pad.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/data/size.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/data/slice.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/data/trim.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/encoding/fromHex.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/encoding/toBytes.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/encoding/toHex.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/errors/getNodeError.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/formatters/extract.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/formatters/transactionRequest.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/keccak256.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/toFunctionSelector.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/hashSignature.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/toSignature.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/normalizeSignature.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/toSignatureHash.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/lru.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/stateOverride.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/stringify.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/number.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/transaction/assertRequest.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/unit/formatEther.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/unit/formatGwei.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/unit/formatUnits.ts","../node_modules/@noble/hashes/src/_assert.ts","../node_modules/@noble/hashes/src/_md.ts","../node_modules/@noble/hashes/src/sha256.ts","../node_modules/@noble/hashes/src/_u64.ts","../node_modules/@noble/hashes/src/sha3.ts","../node_modules/@noble/hashes/src/crypto.ts","../node_modules/@noble/hashes/src/utils.ts","../../../../../src/utils/DateUtil.ts","../../../../../src/utils/NetworkUtil.ts","../node_modules/bignumber.js/bignumber.mjs","../../../../../src/utils/NumberUtil.ts","../../../../../src/utils/InputUtil.ts","../../../../../src/contracts/erc20.ts","../../../../../src/utils/NavigationUtil.ts","../../../../../src/utils/ConstantsUtil.ts","../../../../../src/utils/ThemeUtil.ts","../../../../../src/utils/CoreHelperUtil.ts","../../../../../src/utils/FetchUtil.ts","../../../../../src/utils/StorageUtil.ts","../../../../../src/controllers/AssetController.ts","../../../../../src/controllers/ThemeController.ts","../../../../../src/controllers/ConnectorController.ts","../../../../../src/controllers/EventsController.ts","../../../../../src/controllers/PublicStateController.ts","../../../../../src/controllers/ChainController.ts","../../../../../src/controllers/NetworkController.ts","../../../../../src/controllers/ApiController.ts","../../../../../src/controllers/OptionsController.ts","../../../../../src/controllers/BlockchainApiController.ts","../../../../../src/controllers/SnackController.ts","../../../../../src/controllers/TransactionsController.ts","../../../../../src/controllers/ConnectionController.ts","../../../../../src/utils/SwapApiUtil.ts","../../../../../src/controllers/RouterController.ts","../../../../../src/utils/SwapCalculationUtil.ts","../../../../../src/controllers/SwapController.ts","../../../../../src/controllers/AccountController.ts","../../../../../src/controllers/ModalController.ts","../../../../../src/controllers/OnRampController.ts","../../../../../src/controllers/SendController.ts","../../../../../src/controllers/TooltipController.ts","../../../../../src/utils/EnsUtil.ts","../../../../../src/controllers/EnsController.ts","../../../../../src/utils/AssetUtil.ts","../../../../../src/utils/RouterUtil.ts","../../../index.ts","../../../../../../src/assets/svg/swap-input-mask-bottom.ts","../../../../../../src/assets/svg/swap-input-mask-top.ts","../../../../../src/utils/WebComponentsUtil.ts","../../../../../../src/components/wui-card/styles.ts","../../../../../../src/components/wui-card/index.ts","../../../../../../src/components/wui-icon/styles.ts","../../../../../../src/assets/svg/add.ts","../../../../../../src/assets/svg/all-wallets.ts","../../../../../../src/assets/svg/arrow-bottom-circle.ts","../../../../../../src/assets/svg/app-store.ts","../../../../../../src/assets/svg/apple.ts","../../../../../../src/assets/svg/arrow-bottom.ts","../../../../../../src/assets/svg/arrow-left.ts","../../../../../../src/assets/svg/arrow-right.ts","../../../../../../src/assets/svg/arrow-top.ts","../../../../../../src/assets/svg/bank.ts","../../../../../../src/assets/svg/browser.ts","../../../../../../src/assets/svg/card.ts","../../../../../../src/assets/svg/checkmark-bold.ts","../../../../../../src/assets/svg/checkmark.ts","../../../../../../src/assets/svg/chevron-bottom.ts","../../../../../../src/assets/svg/chevron-left.ts","../../../../../../src/assets/svg/chevron-right.ts","../../../../../../src/assets/svg/chevron-top.ts","../../../../../../src/assets/svg/chrome-store.ts","../../../../../../src/assets/svg/clock.ts","../../../../../../src/assets/svg/close.ts","../../../../../../src/assets/svg/coinPlaceholder.ts","../../../../../../src/assets/svg/compass.ts","../../../../../../src/assets/svg/copy.ts","../../../../../../src/assets/svg/cursor.ts","../../../../../../src/assets/svg/cursor-transparent.ts","../../../../../../src/assets/svg/desktop.ts","../../../../../../src/assets/svg/disconnect.ts","../../../../../../src/assets/svg/discord.ts","../../../../../../src/assets/svg/etherscan.ts","../../../../../../src/assets/svg/extension.ts","../../../../../../src/assets/svg/external-link.ts","../../../../../../src/assets/svg/facebook.ts","../../../../../../src/assets/svg/farcaster.ts","../../../../../../src/assets/svg/filters.ts","../../../../../../src/assets/svg/github.ts","../../../../../../src/assets/svg/google.ts","../../../../../../src/assets/svg/help-circle.ts","../../../../../../src/assets/svg/image.ts","../../../../../../src/assets/svg/info-circle.ts","../../../../../../src/assets/svg/mail.ts","../../../../../../src/assets/svg/mobile.ts","../../../../../../src/assets/svg/more.ts","../../../../../../src/assets/svg/network-placeholder.ts","../../../../../../src/assets/svg/nftPlaceholder.ts","../../../../../../src/assets/svg/off.ts","../../../../../../src/assets/svg/play-store.ts","../../../../../../src/assets/svg/plus.ts","../../../../../../src/assets/svg/qr-code.ts","../../../../../../src/assets/svg/recycle-horizontal.ts","../../../../../../src/assets/svg/refresh.ts","../../../../../../src/assets/svg/search.ts","../../../../../../src/assets/svg/send.ts","../../../../../../src/assets/svg/swapHorizontal.ts","../../../../../../src/assets/svg/swapHorizontalBold.ts","../../../../../../src/assets/svg/swapHorizontalMedium.ts","../../../../../../src/assets/svg/swapHorizontalRoundedBold.ts","../../../../../../src/assets/svg/swapVertical.ts","../../../../../../src/assets/svg/telegram.ts","../../../../../../src/assets/svg/three-dots.ts","../../../../../../src/assets/svg/twitch.ts","../../../../../../src/assets/svg/twitterIcon.ts","../../../../../../src/assets/svg/verify.ts","../../../../../../src/assets/svg/verify-filled.ts","../../../../../../src/assets/svg/wallet-placeholder.ts","../../../../../../src/assets/svg/wallet.ts","../../../../../../src/assets/svg/walletconnect.ts","../../../../../../src/assets/svg/warning-circle.ts","../../../../../../src/assets/svg/lightbulb.ts","../../../../../../src/assets/svg/id.ts","../../../../../../src/assets/svg/x.ts","../../../../../../src/components/wui-icon/index.ts","../../../../../../src/components/wui-image/styles.ts","../../../../../../src/components/wui-image/index.ts","../../../../../../src/components/wui-loading-hexagon/styles.ts","../../../../../../src/components/wui-loading-hexagon/index.ts","../../../../../../src/components/wui-loading-spinner/styles.ts","../../../../../../src/components/wui-loading-spinner/index.ts","../../../../../../src/components/wui-loading-thumbnail/styles.ts","../../../../../../src/components/wui-loading-thumbnail/index.ts","../../../../../../src/components/wui-shimmer/styles.ts","../../../../../../src/components/wui-shimmer/index.ts","../node_modules/lit/node_modules/lit-html/src/directives/class-map.ts","../../../../../../src/components/wui-text/styles.ts","../../../../../../src/components/wui-text/index.ts","../../../../../../src/assets/visual/browser.ts","../../../../../../src/assets/visual/dao.ts","../../../../../../src/assets/visual/defi.ts","../../../../../../src/assets/visual/defiAlt.ts","../../../../../../src/assets/visual/eth.ts","../../../../../../src/assets/visual/layers.ts","../../../../../../src/assets/visual/lock.ts","../../../../../../src/assets/visual/login.ts","../../../../../../src/assets/visual/network.ts","../../../../../../src/assets/visual/nft.ts","../../../../../../src/assets/visual/noun.ts","../../../../../../src/assets/visual/profile.ts","../../../../../../src/assets/visual/system.ts","../../../../../../src/assets/visual/coinbase.ts","../../../../../../src/assets/visual/moonpay.ts","../../../../../../src/assets/visual/stripe.ts","../../../../../../src/assets/visual/paypal.ts","../../../../../../src/assets/visual/onramp-card.ts","../../../../../../src/assets/visual/google.ts","../../../../../../src/assets/visual/pencil.ts","../../../../../../src/assets/visual/lightbulb.ts","../../../../../../src/components/wui-visual/styles.ts","../../../../../../src/components/wui-visual/index.ts","../../../../../src/utils/UiHelperUtil.ts","../../../../../../src/layout/wui-flex/styles.ts","../../../../../../src/layout/wui-flex/index.ts","../../../../../../src/composites/wui-avatar/styles.ts","../../../../../../src/composites/wui-avatar/index.ts","../../../../../../src/composites/wui-icon-box/styles.ts","../../../../../../src/composites/wui-icon-box/index.ts","../../../../../../src/composites/wui-account-button/styles.ts","../../../../../../src/composites/wui-account-button/index.ts","../../../../../../src/composites/wui-wallet-image/styles.ts","../../../../../../src/composites/wui-wallet-image/index.ts","../../../../../../src/composites/wui-all-wallets-image/styles.ts","../../../../../../src/composites/wui-all-wallets-image/index.ts","../../../../../../src/composites/wui-button/styles.ts","../../../../../../src/composites/wui-button/index.ts","../../../../../../src/assets/svg/networkMd.ts","../../../../../../src/composites/wui-card-select-loader/styles.ts","../../../../../../src/composites/wui-card-select-loader/index.ts","../../../../../../src/assets/svg/networkSm.ts","../../../../../../src/assets/svg/networkLg.ts","../../../../../../src/composites/wui-network-image/styles.ts","../../../../../../src/composites/wui-network-image/index.ts","../../../../../../src/composites/wui-card-select/styles.ts","../../../../../../src/composites/wui-card-select/index.ts","../../../../../../src/composites/wui-chip/styles.ts","../../../../../../src/composites/wui-chip/index.ts","../../../../../../src/composites/wui-connect-button/styles.ts","../../../../../../src/composites/wui-connect-button/index.ts","../../../../../../src/composites/wui-cta-button/styles.ts","../../../../../../src/composites/wui-cta-button/index.ts","../../../../../../src/composites/wui-details-group/styles.ts","../../../../../../src/composites/wui-details-group/index.ts","../../../../../../src/composites/wui-details-group-item/styles.ts","../../../../../../src/composites/wui-details-group-item/index.ts","../../../../../../src/composites/wui-dropdown-menu/styles.ts","../../../../../../src/composites/wui-dropdown-menu/index.ts","../../../../../../src/composites/wui-input-text/styles.ts","../../../../../../src/composites/wui-input-text/index.ts","../../../../../../src/composites/wui-email-input/styles.ts","../../../../../../src/composites/wui-email-input/index.ts","../../../../../../src/composites/wui-ens-input/styles.ts","../../../../../../src/composites/wui-ens-input/index.ts","../../../../../../src/composites/wui-icon-link/styles.ts","../../../../../../src/composites/wui-icon-link/index.ts","../../../../../../src/composites/wui-input-element/styles.ts","../../../../../../src/composites/wui-input-element/index.ts","../../../../../../src/composites/wui-input-numeric/styles.ts","../../../../../../src/composites/wui-input-numeric/index.ts","../../../../../../src/composites/wui-link/styles.ts","../../../../../../src/composites/wui-link/index.ts","../../../../../../src/composites/wui-list-item/styles.ts","../../../../../../src/composites/wui-list-item/index.ts","../../../../../src/utils/TypeUtil.ts","../../../../../../src/composites/wui-transaction-visual/styles.ts","../../../../../../src/composites/wui-transaction-visual/index.ts","../../../../../../src/composites/wui-transaction-list-item/styles.ts","../../../../../../src/composites/wui-transaction-list-item/index.ts","../../../../../../src/composites/wui-transaction-list-item-loader/styles.ts","../../../../../../src/composites/wui-transaction-list-item-loader/index.ts","../../../../../../src/composites/wui-tag/styles.ts","../../../../../../src/composites/wui-tag/index.ts","../../../../../../src/composites/wui-list-wallet/styles.ts","../../../../../../src/composites/wui-list-wallet/index.ts","../../../../../../src/composites/wui-logo/styles.ts","../../../../../../src/composites/wui-logo/index.ts","../../../../../../src/composites/wui-logo-select/styles.ts","../../../../../../src/composites/wui-logo-select/index.ts","../../../../../../src/composites/wui-network-button/styles.ts","../../../../../../src/composites/wui-network-button/index.ts","../../../../../../src/composites/wui-otp/styles.ts","../../../../../../src/composites/wui-otp/index.ts","../../../../../src/utils/QrCode.ts","../../../../../../src/composites/wui-qr-code/styles.ts","../../../../../../src/composites/wui-qr-code/index.ts","../../../../../../src/composites/wui-search-bar/styles.ts","../../../../../../src/composites/wui-search-bar/index.ts","../../../../../../src/composites/wui-snackbar/styles.ts","../../../../../../src/composites/wui-snackbar/index.ts","../../../../../../src/composites/wui-tabs/styles.ts","../../../../../../src/composites/wui-tabs/index.ts","../../../../../../src/composites/wui-token-button/styles.ts","../../../../../../src/composites/wui-token-button/index.ts","../../../../../../src/composites/wui-tooltip/styles.ts","../../../../../../src/composites/wui-tooltip/index.ts","../../../../../../src/composites/wui-token-list-item/styles.ts","../../../../../../src/composites/wui-token-list-item/index.ts","../../../../../../src/composites/wui-visual-thumbnail/styles.ts","../../../../../../src/composites/wui-visual-thumbnail/index.ts","../../../../../../src/composites/wui-notice-card/styles.ts","../../../../../../src/composites/wui-notice-card/index.ts","../../../../../../src/composites/wui-list-accordion/styles.ts","../../../../../../src/composites/wui-list-accordion/index.ts","../../../../../../src/composites/wui-list-content/styles.ts","../../../../../../src/composites/wui-list-content/index.ts","../../../../../../src/composites/wui-list-network/styles.ts","../../../../../../src/composites/wui-list-network/index.ts","../../../../../../src/composites/wui-list-wallet-transaction/styles.ts","../../../../../../src/composites/wui-list-wallet-transaction/index.ts","../../../../../../src/composites/wui-promo/styles.ts","../../../../../../src/composites/wui-promo/index.ts","../../../../../../src/composites/wui-balance/styles.ts","../../../../../../src/composites/wui-balance/index.ts","../../../../../../src/composites/wui-profile-button/styles.ts","../../../../../../src/composites/wui-profile-button/index.ts","../../../../../../src/composites/wui-profile-button-v2/styles.ts","../../../../../../src/composites/wui-profile-button-v2/index.ts","../../../../../../src/composites/wui-chip-button/styles.ts","../../../../../../src/composites/wui-chip-button/index.ts","../../../../../../src/composites/wui-compatible-network/styles.ts","../../../../../../src/composites/wui-compatible-network/index.ts","../../../../../../src/composites/wui-banner/styles.ts","../../../../../../src/composites/wui-banner/index.ts","../../../../../../src/composites/wui-banner-img/styles.ts","../../../../../../src/composites/wui-banner-img/index.ts","../../../../../../src/composites/wui-list-token/styles.ts","../../../../../../src/composites/wui-list-token/index.ts","../../../../../../src/composites/wui-list-description/styles.ts","../../../../../../src/composites/wui-list-description/index.ts","../../../../../../src/composites/wui-input-amount/styles.ts","../../../../../../src/composites/wui-input-amount/index.ts","../../../../../../src/composites/wui-preview-item/styles.ts","../../../../../../src/composites/wui-preview-item/index.ts","../../../../../../src/composites/wui-list-account/styles.ts","../../../../../../src/composites/wui-list-account/index.ts","../../../../../../src/composites/wui-icon-button/styles.ts","../../../../../../src/composites/wui-icon-button/index.ts","../../../../../../src/composites/wui-list-button/styles.ts","../../../../../../src/composites/wui-list-button/index.ts","../../../../../../src/composites/wui-list-social/styles.ts","../../../../../../src/composites/wui-list-social/index.ts","../../../../../../src/composites/wui-select/styles.ts","../../../../../../src/composites/wui-select/index.ts","../../../../../../src/layout/wui-grid/styles.ts","../../../../../../src/layout/wui-grid/index.ts","../../../../../../src/layout/wui-separator/styles.ts","../../../../../../src/layout/wui-separator/index.ts","../../../../../src/utils/MathUtil.ts","../../../../../src/utils/TransactionUtil.ts","../../../../src/W3mFrameConstants.ts","../node_modules/zod/lib/index.mjs","../../../../src/W3mFrameSchema.ts","../../../../src/W3mFrameStorage.ts","../../../../src/RegexUtil.ts","../../../../src/W3mFrameHelpers.ts","../../../../src/W3mFrame.ts","../../../../src/W3mFrameLogger.ts","../../../../src/W3mFrameProvider.ts","../node_modules/abitype/src/human-readable/formatAbiParameter.ts","../node_modules/abitype/src/human-readable/formatAbiParameters.ts","../node_modules/abitype/src/human-readable/formatAbiItem.ts","../node_modules/abitype/src/human-readable/runtime/signatures.ts","../node_modules/abitype/src/errors.ts","../node_modules/abitype/src/version.ts","../node_modules/abitype/src/human-readable/errors/abiItem.ts","../node_modules/abitype/src/human-readable/errors/abiParameter.ts","../node_modules/abitype/src/human-readable/errors/signature.ts","../node_modules/abitype/src/human-readable/errors/struct.ts","../node_modules/abitype/src/human-readable/errors/splitParameters.ts","../node_modules/abitype/src/human-readable/runtime/cache.ts","../node_modules/abitype/src/human-readable/runtime/utils.ts","../node_modules/abitype/src/human-readable/runtime/structs.ts","../node_modules/abitype/src/human-readable/parseAbi.ts","../node_modules/abitype/src/regex.ts","../node_modules/lit/node_modules/lit-html/src/directives/if-defined.ts","../node_modules/lit/node_modules/lit-html/src/directive-helpers.ts","../node_modules/lit/node_modules/lit-html/src/async-directive.ts","../node_modules/lit/node_modules/lit-html/src/directives/ref.ts","../node_modules/lit-element/node_modules/@lit/reactive-element/src/css-tag.ts","../node_modules/lit-element/node_modules/@lit/reactive-element/src/reactive-element.ts","../node_modules/lit-element/node_modules/lit-html/src/lit-html.ts","../node_modules/lit-element/src/lit-element.ts","../node_modules/lit/node_modules/@lit/reactive-element/src/decorators/property.ts","../node_modules/lit/node_modules/@lit/reactive-element/src/decorators/state.ts","../node_modules/lit/node_modules/@lit/reactive-element/src/css-tag.ts","../node_modules/lit/node_modules/@lit/reactive-element/src/reactive-element.ts","../node_modules/lit/node_modules/lit-html/src/directive.ts","../node_modules/lit/node_modules/lit-html/src/lit-html.ts","../node_modules/multiformats/esm/vendor/base-x.js","../node_modules/multiformats/esm/src/bytes.js","../node_modules/multiformats/esm/src/bases/base.js","../node_modules/multiformats/esm/src/bases/identity.js","../node_modules/multiformats/esm/src/bases/base2.js","../node_modules/multiformats/esm/src/bases/base8.js","../node_modules/multiformats/esm/src/bases/base10.js","../node_modules/multiformats/esm/src/bases/base16.js","../node_modules/multiformats/esm/src/bases/base32.js","../node_modules/multiformats/esm/src/bases/base36.js","../node_modules/multiformats/esm/src/bases/base58.js","../node_modules/multiformats/esm/src/bases/base64.js","../node_modules/multiformats/esm/src/bases/base256emoji.js","../node_modules/multiformats/esm/vendor/varint.js","../node_modules/multiformats/esm/src/varint.js","../node_modules/multiformats/esm/src/hashes/digest.js","../node_modules/multiformats/esm/src/hashes/hasher.js","../node_modules/multiformats/esm/src/hashes/sha2-browser.js","../node_modules/multiformats/esm/src/hashes/identity.js","../node_modules/multiformats/esm/src/codecs/raw.js","../node_modules/multiformats/esm/src/codecs/json.js","../node_modules/multiformats/esm/src/cid.js","../node_modules/multiformats/esm/src/basics.js","../node_modules/text-encoding-utf-8/lib/encoding.lib.mjs","../node_modules/uint8arrays/esm/src/alloc.js","../node_modules/uint8arrays/esm/src/concat.js","../node_modules/uint8arrays/esm/src/util/bases.js","../node_modules/uint8arrays/esm/src/from-string.js","../node_modules/uint8arrays/esm/src/to-string.js","../node_modules/proxy-compare/src/index.ts","../node_modules/valtio/esm/vanilla.mjs","../node_modules/valtio/esm/vanilla/utils.mjs","../node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/viem/constants/contract.ts","../node_modules/viem/constants/contracts.ts","../node_modules/viem/actions/public/call.ts","../node_modules/viem/utils/errors/getCallError.ts","../node_modules/viem/constants/abis.ts","../node_modules/viem/constants/solidity.ts","../node_modules/viem/constants/unit.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/errors/address.ts","../node_modules/viem/errors/version.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/chain.ts","../node_modules/viem/utils/abi/formatAbiItemWithArgs.ts","../node_modules/viem/errors/contract.ts","../node_modules/viem/errors/data.ts","../node_modules/viem/errors/encoding.ts","../node_modules/viem/errors/node.ts","../node_modules/viem/errors/request.ts","../node_modules/viem/errors/stateOverride.ts","../node_modules/viem/errors/transaction.ts","../node_modules/viem/errors/utils.ts","../node_modules/viem/utils/encoding/fromBytes.ts","../node_modules/viem/utils/abi/decodeAbiParameters.ts","../node_modules/viem/utils/abi/decodeErrorResult.ts","../node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/viem/utils/abi/formatAbiItem.ts","../node_modules/viem/utils/hash/toEventSelector.ts","../node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/address/isAddress.ts","../node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/utils/data/concat.ts","../node_modules/viem/utils/data/isHex.ts","../node_modules/viem/utils/data/pad.ts","../node_modules/viem/utils/data/size.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/data/trim.ts","../node_modules/viem/utils/encoding/fromHex.ts","../node_modules/viem/utils/encoding/toBytes.ts","../node_modules/viem/utils/encoding/toHex.ts","../node_modules/viem/utils/errors/getNodeError.ts","../node_modules/viem/utils/formatters/extract.ts","../node_modules/viem/utils/formatters/formatter.ts","../node_modules/viem/utils/formatters/transactionRequest.ts","../node_modules/viem/utils/hash/keccak256.ts","../node_modules/viem/utils/hash/toFunctionSelector.ts","../node_modules/viem/utils/hash/hashSignature.ts","../node_modules/viem/utils/hash/toSignature.ts","../node_modules/viem/utils/hash/normalizeSignature.ts","../node_modules/viem/utils/hash/toSignatureHash.ts","../node_modules/viem/utils/lru.ts","../node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/viem/utils/stateOverride.ts","../node_modules/viem/utils/stringify.ts","../node_modules/viem/utils/transaction/assertRequest.ts","../node_modules/viem/utils/regex.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/utils/unit/formatEther.ts","../node_modules/viem/utils/unit/formatGwei.ts","../node_modules/viem/utils/unit/formatUnits.ts","../node_modules/@babel/runtime/helpers/esm/extends.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js","../webpack/bootstrap","../webpack/runtime/compat get default export","../webpack/runtime/create fake namespace object","../webpack/runtime/define property getters","../webpack/runtime/ensure chunk","../webpack/runtime/get javascript chunk filename","../webpack/runtime/get mini-css chunk filename","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/load script","../webpack/runtime/make namespace object","../webpack/runtime/node module decorator","../webpack/runtime/publicPath","../webpack/runtime/jsonp chunk loading","../webpack/runtime/nonce","../node_modules/@sentry/utils/src/version.ts","../node_modules/@sentry/utils/src/worldwide.ts","../node_modules/@sentry/core/src/constants.ts","../node_modules/@sentry/core/src/carrier.ts","../node_modules/@sentry/utils/src/is.ts","../node_modules/@sentry/utils/src/browser.ts","../node_modules/@sentry/utils/src/debug-build.ts","../node_modules/@sentry/utils/src/logger.ts","../node_modules/@sentry/utils/src/string.ts","../node_modules/@sentry/utils/src/object.ts","../node_modules/@sentry/utils/src/misc.ts","../node_modules/@sentry/utils/src/propagationContext.ts","../node_modules/@sentry/utils/src/time.ts","../node_modules/@sentry/core/src/session.ts","../node_modules/@sentry/core/src/utils/spanOnScope.ts","../node_modules/@sentry/core/src/scope.ts","../node_modules/@sentry/core/src/asyncContext/stackStrategy.ts","../node_modules/@sentry/core/src/defaultScopes.ts","../node_modules/@sentry/core/src/asyncContext/index.ts","../node_modules/@sentry/core/src/currentScopes.ts","../node_modules/@sentry/utils/src/stacktrace.ts","../node_modules/@sentry/utils/src/normalize.ts","../node_modules/@sentry/utils/src/memo.ts","../node_modules/@sentry/utils/src/syncpromise.ts","../node_modules/@sentry/core/src/debug-build.ts","../node_modules/@sentry/core/src/eventProcessors.ts","../node_modules/@sentry/utils/src/baggage.ts","../node_modules/@sentry/core/src/semanticAttributes.ts","../node_modules/@sentry/utils/src/tracing.ts","../node_modules/@sentry/core/src/metrics/metric-summary.ts","../node_modules/@sentry/core/src/tracing/spanstatus.ts","../node_modules/@sentry/core/src/utils/spanUtils.ts","../node_modules/@sentry/core/src/tracing/dynamicSamplingContext.ts","../node_modules/@sentry/core/src/utils/applyScopeDataToEvent.ts","../node_modules/@sentry/core/src/utils/prepareEvent.ts","../node_modules/@sentry/core/src/exports.ts","../node_modules/@sentry/core/src/integration.ts","../node_modules/@sentry/core/src/integrations/inboundfilters.ts","../node_modules/@sentry/core/src/integrations/functiontostring.ts","../node_modules/@sentry/core/src/integrations/dedupe.ts","../node_modules/@sentry/core/src/sdk.ts","../node_modules/@sentry/utils/src/supports.ts","../node_modules/@sentry/utils/src/instrument/handlers.ts","../node_modules/@sentry/utils/src/vendor/supportsHistory.ts","../node_modules/@sentry-internal/browser-utils/src/types.ts","../node_modules/@sentry-internal/browser-utils/src/instrument/history.ts","../node_modules/@sentry/utils/src/dsn.ts","../node_modules/@sentry/utils/src/envelope.ts","../node_modules/@sentry/utils/src/error.ts","../node_modules/@sentry/core/src/api.ts","../node_modules/@sentry/core/src/utils/parseSampleRate.ts","../node_modules/@sentry/core/src/baseclient.ts","../node_modules/@sentry/core/src/envelope.ts","../node_modules/@sentry/utils/src/clientreport.ts","../node_modules/@sentry/core/src/utils/sdkMetadata.ts","../node_modules/@sentry/browser/src/debug-build.ts","../node_modules/@sentry/browser/src/eventbuilder.ts","../node_modules/@sentry/browser/src/helpers.ts","../node_modules/@sentry/browser/src/client.ts","../node_modules/@sentry/utils/src/env.ts","../node_modules/@sentry/browser/src/userfeedback.ts","../node_modules/@sentry-internal/browser-utils/src/instrument/dom.ts","../node_modules/@sentry-internal/browser-utils/src/instrument/xhr.ts","../node_modules/@sentry/core/src/breadcrumbs.ts","../node_modules/@sentry/utils/src/instrument/console.ts","../node_modules/@sentry/utils/src/instrument/fetch.ts","../node_modules/@sentry/utils/src/severity.ts","../node_modules/@sentry/utils/src/url.ts","../node_modules/@sentry/browser/src/integrations/breadcrumbs.ts","../node_modules/@sentry/browser/src/integrations/browserapierrors.ts","../node_modules/@sentry/utils/src/instrument/globalError.ts","../node_modules/@sentry/utils/src/instrument/globalUnhandledRejection.ts","../node_modules/@sentry/browser/src/integrations/globalhandlers.ts","../node_modules/@sentry/browser/src/integrations/httpcontext.ts","../node_modules/@sentry/utils/src/aggregate-errors.ts","../node_modules/@sentry/browser/src/integrations/linkederrors.ts","../node_modules/@sentry/browser/src/stack-parsers.ts","../node_modules/@sentry-internal/browser-utils/src/debug-build.ts","../node_modules/@sentry-internal/browser-utils/src/getNativeImplementation.ts","../node_modules/@sentry/utils/src/promisebuffer.ts","../node_modules/@sentry/utils/src/ratelimit.ts","../node_modules/@sentry/core/src/transports/base.ts","../node_modules/@sentry/browser/src/transports/fetch.ts","../node_modules/@sentry/browser/src/sdk.ts","../node_modules/@sentry/core/src/utils/hasTracingEnabled.ts","../node_modules/@sentry/core/src/tracing/sentryNonRecordingSpan.ts","../node_modules/@sentry/core/src/tracing/measurement.ts","../node_modules/@sentry/core/src/tracing/utils.ts","../node_modules/@sentry/core/src/tracing/sentrySpan.ts","../node_modules/@sentry/core/src/tracing/logSpans.ts","../node_modules/@sentry/core/src/tracing/trace.ts","../node_modules/@sentry/core/src/tracing/sampling.ts","../node_modules/@sentry/utils/src/buildPolyfills/_optionalChain.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/bindReporter.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getNavigationEntry.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getActivationStart.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/initMetric.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/generateUniqueID.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/observe.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/onHidden.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/runOnce.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/getVisibilityWatcher.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/whenActivated.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/onFCP.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getCLS.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getFID.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getINP.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/getLCP.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/web-vitals/onTTFB.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/instrument.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/utils.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/cls.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/browserMetrics.ts","../node_modules/@sentry-internal/browser-utils/src/metrics/inp.ts","../node_modules/@sentry/core/src/tracing/idleSpan.ts","../node_modules/@sentry/core/src/tracing/errors.ts","../node_modules/@sentry/core/src/fetch.ts","../node_modules/@sentry/browser/src/tracing/request.ts","../node_modules/@sentry/browser/src/tracing/browserTracingIntegration.ts","../node_modules/@sentry/browser/src/tracing/backgroundtab.ts","../node_modules/@sentry/core/src/utils/isSentryRequestUrl.ts","../node_modules/@sentry/utils/src/node.ts","../node_modules/@sentry/utils/src/isBrowser.ts","../node_modules/@sentry-internal/replay/src/constants.ts","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/utils.js","../node_modules/@sentry/utils/src/buildPolyfills/_nullishCoalesce.ts","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/types/dist/rrweb-types.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/error-handler.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/cross-origin-iframe-mirror.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/stylesheet-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/processed-node-manager.js","../node_modules/node_modules/@sentry-internal/rrweb/es/rrweb/packages/rrweb/src/record/index.js","../node_modules/@sentry-internal/replay/src/debug-build.ts","../node_modules/@sentry-internal/replay/src/util/logger.ts","../node_modules/@sentry-internal/replay/src/types/rrweb.ts","../node_modules/@sentry-internal/replay/src/util/timestamp.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/addBreadcrumbEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/domUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/onWindowOpen.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleClick.ts","../node_modules/@sentry-internal/replay/src/util/createBreadcrumb.ts","../node_modules/node_modules/@sentry-internal/rrweb-snapshot/es/rrweb-snapshot.js","../node_modules/@sentry-internal/replay/src/coreHandlers/util/getAttributesToRecord.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleDom.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleKeyboardEvent.ts","../node_modules/@sentry-internal/replay/src/util/createPerformanceEntries.ts","../node_modules/@sentry-internal/replay-worker/build/esm/worker.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/error.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferArray.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/WorkerHandler.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferCompressionWorker.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/EventBufferProxy.ts","../node_modules/@sentry-internal/replay/src/eventBuffer/index.ts","../node_modules/@sentry-internal/replay-worker/build/esm/index.js","../node_modules/@sentry-internal/replay/src/util/hasSessionStorage.ts","../node_modules/@sentry-internal/replay/src/session/clearSession.ts","../node_modules/@sentry-internal/replay/src/util/isSampled.ts","../node_modules/@sentry-internal/replay/src/session/Session.ts","../node_modules/@sentry-internal/replay/src/session/saveSession.ts","../node_modules/@sentry-internal/replay/src/session/createSession.ts","../node_modules/@sentry-internal/replay/src/util/isExpired.ts","../node_modules/@sentry-internal/replay/src/util/isSessionExpired.ts","../node_modules/@sentry-internal/replay/src/session/shouldRefreshSession.ts","../node_modules/@sentry-internal/replay/src/session/loadOrCreateSession.ts","../node_modules/@sentry-internal/replay/src/session/fetchSession.ts","../node_modules/@sentry-internal/replay/src/util/addEvent.ts","../node_modules/@sentry-internal/replay/src/util/eventUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleAfterSendEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleBeforeSendEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleBreadcrumbs.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleGlobalEvent.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/addFeedbackBreadcrumb.ts","../node_modules/@sentry-internal/replay/src/util/isRrwebError.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/shouldSampleForBufferEvent.ts","../node_modules/@sentry-internal/replay/src/util/createPerformanceSpans.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleHistory.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/addNetworkBreadcrumb.ts","../node_modules/@sentry-internal/replay/src/util/shouldFilterRequest.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/networkUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/fetchUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/util/xhrUtils.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/handleNetworkBreadcrumbs.ts","../node_modules/@sentry-internal/replay/src/util/addGlobalListeners.ts","../node_modules/@sentry-internal/replay/src/util/addMemoryEntry.ts","../node_modules/@sentry-internal/replay/src/util/handleRecordingEmit.ts","../node_modules/@sentry-internal/replay/src/util/sendReplayRequest.ts","../node_modules/@sentry-internal/replay/src/util/prepareRecordingData.ts","../node_modules/@sentry-internal/replay/src/util/prepareReplayEvent.ts","../node_modules/@sentry-internal/replay/src/util/createReplayEnvelope.ts","../node_modules/@sentry-internal/replay/src/util/sendReplay.ts","../node_modules/@sentry-internal/replay/src/util/throttle.ts","../node_modules/@sentry-internal/replay/src/replay.ts","../node_modules/@sentry-internal/replay/src/util/debounce.ts","../node_modules/@sentry-internal/replay/src/coreHandlers/performanceObserver.ts","../node_modules/@sentry-internal/replay/src/util/getPrivacyOptions.ts","../node_modules/@sentry-internal/replay/src/integration.ts","../node_modules/@sentry-internal/replay/src/util/maskAttribute.ts","../node_modules/tslib/tslib.es6.mjs","../node_modules/styled-components/node_modules/stylis/src/Enum.js","../node_modules/styled-components/node_modules/stylis/src/Utility.js","../node_modules/styled-components/node_modules/stylis/src/Tokenizer.js","../node_modules/styled-components/node_modules/stylis/src/Serializer.js","../node_modules/styled-components/node_modules/stylis/src/Prefixer.js","../node_modules/styled-components/node_modules/stylis/src/Middleware.js","../node_modules/styled-components/node_modules/stylis/src/Parser.js","../node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../node_modules/styled-components/src/constants.ts","../node_modules/styled-components/src/utils/empties.ts","../node_modules/styled-components/src/utils/checkDynamicCreation.ts","../node_modules/styled-components/src/utils/determineTheme.ts","../node_modules/styled-components/src/utils/domElements.ts","../node_modules/styled-components/src/utils/escape.ts","../node_modules/styled-components/src/utils/generateAlphabeticName.ts","../node_modules/styled-components/src/utils/hash.ts","../node_modules/styled-components/src/utils/generateComponentId.ts","../node_modules/styled-components/src/utils/getComponentName.ts","../node_modules/styled-components/src/utils/isTag.ts","../node_modules/styled-components/src/utils/hoist.ts","../node_modules/styled-components/src/utils/isFunction.ts","../node_modules/styled-components/src/utils/isStyledComponent.ts","../node_modules/styled-components/src/utils/joinStrings.ts","../node_modules/styled-components/src/utils/isPlainObject.ts","../node_modules/styled-components/src/utils/mixinDeep.ts","../node_modules/styled-components/src/utils/setToString.ts","../node_modules/styled-components/src/utils/error.ts","../node_modules/styled-components/src/sheet/GroupedTag.ts","../node_modules/styled-components/src/sheet/GroupIDAllocator.ts","../node_modules/styled-components/src/sheet/Rehydration.ts","../node_modules/styled-components/src/utils/nonce.ts","../node_modules/styled-components/src/sheet/dom.ts","../node_modules/styled-components/src/sheet/Tag.ts","../node_modules/styled-components/src/sheet/Sheet.ts","../node_modules/styled-components/src/utils/stylis.ts","../node_modules/styled-components/src/models/StyleSheetManager.tsx","../node_modules/styled-components/src/models/Keyframes.ts","../node_modules/styled-components/src/utils/hyphenateStyleName.ts","../node_modules/styled-components/src/utils/flatten.ts","../node_modules/styled-components/src/utils/addUnitIfNeeded.ts","../node_modules/styled-components/src/utils/isStatelessFunction.ts","../node_modules/styled-components/src/utils/isStaticRules.ts","../node_modules/styled-components/src/models/ComponentStyle.ts","../node_modules/styled-components/src/models/ThemeProvider.tsx","../node_modules/styled-components/src/models/StyledComponent.ts","../node_modules/styled-components/src/utils/generateDisplayName.ts","../node_modules/styled-components/src/utils/interleave.ts","../node_modules/styled-components/src/constructors/css.ts","../node_modules/styled-components/src/constructors/constructWithOptions.ts","../node_modules/styled-components/src/constructors/styled.tsx","../node_modules/styled-components/src/models/GlobalStyle.ts","../node_modules/styled-components/src/models/ServerStyleSheet.tsx","../node_modules/styled-components/src/base.ts","../node_modules/clsx/dist/clsx.mjs","../../../../src/ConstantsUtil.ts","../../../../src/PresetsUtil.ts","../../../../src/HelpersUtil.ts","../../../../src/TypeUtil.ts","../../../../src/client.ts","../../../../../../src/modal/w3m-account-button/index.ts","../../../../../../src/modal/w3m-button/styles.ts","../../../../../../src/modal/w3m-button/index.ts","../../../../../../src/modal/w3m-connect-button/index.ts","../../../../../../src/modal/w3m-network-button/styles.ts","../../../../../../src/modal/w3m-network-button/index.ts","../../../../../../src/modal/w3m-router/styles.ts","../../../../../../src/modal/w3m-router/index.ts","../../../../../../src/modal/w3m-onramp-widget/styles.ts","../../../../../../src/modal/w3m-onramp-widget/index.ts","../../../../../../src/views/w3m-account-settings-view/index.ts","../../../../../../src/views/w3m-account-view/index.ts","../../../../../../src/views/w3m-all-wallets-view/index.ts","../../../../../../src/views/w3m-buy-in-progress-view/styles.ts","../../../../../../src/views/w3m-buy-in-progress-view/index.ts","../../../../../../src/views/w3m-connect-view/styles.ts","../../../../../../src/views/w3m-connect-view/index.ts","../../../../../../src/utils/w3m-connecting-widget/styles.ts","../../../../../../src/utils/w3m-connecting-widget/index.ts","../../../../../../src/views/w3m-connecting-external-view/index.ts","../../../../../../src/views/w3m-connecting-multi-chain-view/styles.ts","../../../../../../src/views/w3m-connecting-multi-chain-view/index.ts","../../../../../../src/views/w3m-connecting-wc-view/index.ts","../../../../../../src/views/w3m-choose-account-name-view/styles.ts","../../../../../../src/views/w3m-choose-account-name-view/index.ts","../../../../../../src/views/w3m-downloads-view/index.ts","../../../../../../src/views/w3m-get-wallet-view/index.ts","../../../../../../src/views/w3m-register-account-name-view/styles.ts","../../../../../../src/views/w3m-register-account-name-view/index.ts","../../../../../../src/views/w3m-register-account-name-success-view/styles.ts","../../../../../../src/views/w3m-register-account-name-success-view/index.ts","../../../../../../src/views/w3m-network-switch-view/styles.ts","../../../../../../src/views/w3m-network-switch-view/index.ts","../../../../../../src/views/w3m-networks-view/styles.ts","../../../../../../src/views/w3m-networks-view/index.ts","../../../../../../src/views/w3m-onramp-activity-view/styles.ts","../../../../../../src/views/w3m-onramp-activity-view/index.ts","../../../../../../src/views/w3m-onramp-fiat-select-view/styles.ts","../../../../../../src/views/w3m-onramp-fiat-select-view/index.ts","../../../../../../src/views/w3m-onramp-providers-view/index.ts","../../../../../../src/views/w3m-onramp-tokens-select-view/styles.ts","../../../../../../src/views/w3m-onramp-tokens-select-view/index.ts","../../../../../../src/views/w3m-swap-view/styles.ts","../../../../../../src/views/w3m-swap-view/index.ts","../../../../../../src/views/w3m-switch-active-chain-view/styles.ts","../../../../../../src/views/w3m-switch-active-chain-view/index.ts","../../../../../../src/views/w3m-swap-preview-view/styles.ts","../../../../../../src/views/w3m-swap-preview-view/index.ts","../../../../../../src/views/w3m-swap-select-token-view/styles.ts","../../../../../../src/views/w3m-swap-select-token-view/index.ts","../../../../../../src/views/w3m-transactions-view/styles.ts","../../../../../../src/views/w3m-transactions-view/index.ts","../../../../../../src/views/w3m-what-is-a-network-view/index.ts","../../../../../../src/views/w3m-what-is-a-wallet-view/index.ts","../../../../../../src/views/w3m-what-is-a-buy-view/index.ts","../../../../../../src/utils/w3m-email-otp-widget/styles.ts","../../../../../../src/utils/w3m-email-otp-widget/index.ts","../../../../../../src/views/w3m-email-verify-otp-view/index.ts","../../../../../../src/views/w3m-email-verify-device-view/styles.ts","../../../../../../src/views/w3m-email-verify-device-view/index.ts","../../../../../../src/views/w3m-approve-transaction-view/styles.ts","../../../../../../src/views/w3m-approve-transaction-view/index.ts","../../../../../../src/views/w3m-upgrade-wallet-view/index.ts","../../../../../../src/views/w3m-upgrade-to-smart-account-view/index.ts","../../../../../../src/views/w3m-update-email-wallet-view/styles.ts","../../../../../../src/views/w3m-update-email-wallet-view/index.ts","../../../../../../src/views/w3m-update-email-primary-otp-view/index.ts","../../../../../../src/views/w3m-update-email-secondary-otp-view/index.ts","../../../../../../src/views/w3m-unsupported-chain-view/styles.ts","../../../../../../src/views/w3m-unsupported-chain-view/index.ts","../../../../../../src/views/w3m-wallet-receive-view/styles.ts","../../../../../../src/views/w3m-wallet-receive-view/index.ts","../../../../../../src/views/w3m-wallet-compatible-networks-view/styles.ts","../../../../../../src/views/w3m-wallet-compatible-networks-view/index.ts","../../../../../../src/views/w3m-wallet-send-view/styles.ts","../../../../../../src/views/w3m-wallet-send-view/index.ts","../../../../../../src/views/w3m-wallet-send-select-token-view/styles.ts","../../../../../../src/views/w3m-wallet-send-select-token-view/index.ts","../../../../../../src/views/w3m-wallet-send-preview-view/styles.ts","../../../../../../src/views/w3m-wallet-send-preview-view/index.ts","../../../../../../src/views/w3m-connect-wallets-view/styles.ts","../../../../../../src/views/w3m-connect-wallets-view/index.ts","../../../../../../src/views/w3m-connect-socials-view/styles.ts","../../../../../../src/views/w3m-connect-socials-view/index.ts","../../../../../../src/views/w3m-connecting-social-view/styles.ts","../../../../../../src/views/w3m-connecting-social-view/index.ts","../../../../../../src/views/w3m-profile-view/styles.ts","../../../../../../src/views/w3m-profile-view/index.ts","../../../../../../src/views/w3m-select-addresses-view/styles.ts","../../../../../../src/views/w3m-select-addresses-view/index.ts","../../../../../../src/views/w3m-switch-address-view/styles.ts","../../../../../../src/views/w3m-switch-address-view/index.ts","../../../../../../src/views/w3m-connecting-farcaster-view/styles.ts","../../../../../../src/views/w3m-connecting-farcaster-view/index.ts","../../../../../../src/partials/w3m-all-wallets-list/styles.ts","../../../../../src/utils/markWalletsAsInstalled.ts","../../../../../../src/partials/w3m-all-wallets-list/index.ts","../../../../../../src/partials/w3m-all-wallets-list-item/styles.ts","../../../../../../src/partials/w3m-all-wallets-list-item/index.ts","../../../../../../src/partials/w3m-all-wallets-search/styles.ts","../../../../../../src/partials/w3m-all-wallets-search/index.ts","../../../../../../src/partials/w3m-connecting-header/index.ts","../../../../../../src/partials/w3m-connecting-wc-browser/index.ts","../../../../../../src/partials/w3m-connecting-wc-desktop/index.ts","../../../../../../src/partials/w3m-connecting-wc-mobile/index.ts","../../../../../../src/partials/w3m-connecting-wc-qrcode/styles.ts","../../../../../../src/partials/w3m-connecting-wc-qrcode/index.ts","../../../../../../src/partials/w3m-connecting-wc-unsupported/index.ts","../../../../../../src/partials/w3m-connecting-wc-web/index.ts","../../../../../../src/partials/w3m-swap-details/styles.ts","../../../../../../src/partials/w3m-swap-details/index.ts","../../../../../../src/partials/w3m-swap-input/styles.ts","../../../../../../src/partials/w3m-swap-input/index.ts","../../../../../../src/partials/w3m-swap-input-skeleton/styles.ts","../../../../../../src/partials/w3m-swap-input-skeleton/index.ts","../../../../../../src/partials/w3m-header/styles.ts","../../../../../../src/partials/w3m-header/index.ts","../../../../../../src/partials/w3m-help-widget/index.ts","../../../../../../src/partials/w3m-onramp-activity-item/styles.ts","../../../../../../src/partials/w3m-onramp-activity-item/index.ts","../../../../../../src/partials/w3m-onramp-input/styles.ts","../../../../../../src/partials/w3m-onramp-input/index.ts","../../../../../../src/partials/w3m-onramp-provider-item/styles.ts","../../../../../../src/partials/w3m-onramp-provider-item/index.ts","../../../../../../src/partials/w3m-legal-footer/styles.ts","../../../../../../src/partials/w3m-legal-footer/index.ts","../../../../../../src/partials/w3m-mobile-download-links/styles.ts","../../../../../../src/partials/w3m-mobile-download-links/index.ts","../../../../../../src/partials/w3m-onramp-providers-footer/styles.ts","../../../../../../src/partials/w3m-onramp-providers-footer/index.ts","../../../../../../src/partials/w3m-snackbar/styles.ts","../../../../../../src/partials/w3m-snackbar/index.ts","../../../../../../src/partials/w3m-email-login-widget/styles.ts","../../../../../../src/partials/w3m-email-login-widget/index.ts","../../../../../../src/partials/w3m-account-default-widget/styles.ts","../../../../../../src/partials/w3m-account-default-widget/index.ts","../../../../../../src/partials/w3m-account-wallet-features-widget/styles.ts","../../../../../../src/partials/w3m-account-wallet-features-widget/index.ts","../../../../../../src/partials/w3m-account-activity-widget/styles.ts","../../../../../../src/partials/w3m-account-activity-widget/index.ts","../../../../../../src/partials/w3m-account-nfts-widget/styles.ts","../../../../../../src/partials/w3m-account-nfts-widget/index.ts","../../../../../../src/partials/w3m-account-tokens-widget/styles.ts","../../../../../../src/partials/w3m-account-tokens-widget/index.ts","../../../../../../src/partials/w3m-activity-list/styles.ts","../../../../../../src/partials/w3m-activity-list/index.ts","../../../../../../src/partials/w3m-input-token/styles.ts","../../../../../../src/partials/w3m-input-token/index.ts","../../../../../../src/partials/w3m-input-address/styles.ts","../../../../../../src/partials/w3m-input-address/index.ts","../../../../../../src/partials/w3m-wallet-send-details/styles.ts","../../../../../../src/partials/w3m-wallet-send-details/index.ts","../../../../../../src/partials/w3m-tooltip/styles.ts","../../../../../../src/partials/w3m-tooltip/index.ts","../../../../../../src/partials/w3m-tooltip-trigger/styles.ts","../../../../../../src/partials/w3m-tooltip-trigger/index.ts","../../../../../../src/partials/w3m-social-login-widget/styles.ts","../../../../../../src/partials/w3m-social-login-widget/index.ts","../../../../../../src/partials/w3m-wallet-login-list/index.ts","../../../../../../src/partials/w3m-social-login-list/styles.ts","../../../../../../src/partials/w3m-social-login-list/index.ts","../../../../../../src/partials/w3m-connect-announced-widget/index.ts","../../../../../../src/partials/w3m-connect-custom-widget/index.ts","../../../../../src/utils/WalletUtil.ts","../../../../../../src/partials/w3m-connect-featured-widget/index.ts","../../../../../../src/partials/w3m-connect-injected-widget/index.ts","../../../../../../src/partials/w3m-connect-multi-chain-widget/index.ts","../../../../../../src/partials/w3m-connect-coinbase-widget/index.ts","../../../../../../src/partials/w3m-connect-external-widget/index.ts","../../../../../../src/partials/w3m-connect-recent-widget/index.ts","../../../../../../src/partials/w3m-connect-recommended-widget/index.ts","../../../../../../src/partials/w3m-connect-walletconnect-widget/index.ts","../../../../../../src/partials/w3m-connector-list/styles.ts","../../../../../../src/partials/w3m-connector-list/index.ts","../../../../../../src/partials/w3m-all-wallets-widget/index.ts","../../../../../../src/partials/w3m-account-auth-button/index.ts","../node_modules/@wagmi/core/src/version.ts","../node_modules/@wagmi/core/src/errors/base.ts","../node_modules/@wagmi/core/src/utils/getVersion.ts","../node_modules/@wagmi/core/src/errors/config.ts","../node_modules/@wagmi/core/src/errors/connector.ts","../node_modules/@wagmi/core/src/actions/switchChain.ts","../node_modules/@wagmi/core/src/actions/connect.ts","../node_modules/@wagmi/core/src/actions/reconnect.ts","../node_modules/@wagmi/core/src/actions/disconnect.ts","../node_modules/viem/errors/account.ts","../node_modules/viem/actions/wallet/signMessage.ts","../node_modules/@wagmi/core/src/utils/getAction.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/errors/rpc.ts","../node_modules/viem/utils/promise/withDedupe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/@wagmi/core/src/actions/getConnectorClient.ts","../node_modules/viem/clients/transports/custom.ts","../node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../node_modules/viem/experimental/eip7702/utils/recoverAuthorizationAddress.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/getTransactionCount.ts","../node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/viem/utils/hash/sha256.ts","../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../node_modules/viem/constants/blob.ts","../node_modules/viem/constants/kzg.ts","../node_modules/viem/errors/blob.ts","../node_modules/viem/utils/blob/toBlobSidecars.ts","../node_modules/viem/utils/blob/toBlobs.ts","../node_modules/viem/utils/transaction/getTransactionType.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/@wagmi/core/src/actions/getAccount.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/@wagmi/core/src/actions/waitForTransactionReceipt.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/utils/chain/assertCurrentChain.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/actions/wallet/sendTransaction.ts","../node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/viem/actions/wallet/writeContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/@wagmi/core/src/actions/writeContract.ts","../node_modules/@wagmi/core/src/actions/simulateContract.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/@wagmi/core/src/actions/getEnsAvatar.ts","../node_modules/@wagmi/core/src/actions/watchConnectors.ts","../node_modules/@wagmi/core/src/utils/deepEqual.ts","../node_modules/@wagmi/core/src/actions/watchAccount.ts","../node_modules/@wagmi/core/src/actions/getConnections.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/@wagmi/core/src/utils/getUnit.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/@wagmi/core/src/actions/readContract.ts","../node_modules/@wagmi/core/src/actions/readContracts.ts","../node_modules/@wagmi/core/src/actions/multicall.ts","../node_modules/@wagmi/core/src/actions/getBalance.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/chains/definitions/mainnet.ts","../node_modules/viem/utils/unit/parseUnits.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/utils/rpc/id.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/utils/rpc/http.ts","../node_modules/viem/clients/transports/fallback.ts","../../../../../../adapters/evm/wagmi/utils/helpers.ts","../node_modules/@adraffy/ens-normalize/dist/index.mjs","../node_modules/viem/utils/ens/normalize.ts","../../../../../../adapters/evm/wagmi/client.ts","../node_modules/@wagmi/core/src/actions/signMessage.ts","../node_modules/@wagmi/core/src/actions/estimateGas.ts","../node_modules/@wagmi/core/src/actions/prepareTransactionRequest.ts","../node_modules/@wagmi/core/src/actions/sendTransaction.ts","../node_modules/@wagmi/core/src/actions/getEnsAddress.ts","../node_modules/@wagmi/core/src/actions/switchAccount.ts","../node_modules/@wagmi/core/src/actions/getEnsName.ts","../node_modules/mipd/src/store.ts","../node_modules/mipd/src/utils.ts","../node_modules/@wagmi/core/node_modules/zustand/esm/middleware.mjs","../node_modules/@wagmi/core/node_modules/zustand/esm/vanilla.mjs","../node_modules/@wagmi/core/src/connectors/injected.ts","../node_modules/@wagmi/core/src/createEmitter.ts","../node_modules/@wagmi/core/src/utils/deserialize.ts","../node_modules/@wagmi/core/src/utils/serialize.ts","../node_modules/@wagmi/core/src/createStorage.ts","../node_modules/@wagmi/core/src/utils/uid.ts","../../../../../../utils/library/react/index.ts","../../../../../exports/react/index.ts","../node_modules/@wagmi/core/src/createConfig.ts","../node_modules/@wagmi/connectors/src/walletConnect.ts","../node_modules/@wagmi/core/src/utils/extractRpcUrls.ts","../node_modules/@wagmi/connectors/src/coinbaseWallet.ts","../node_modules/@remix-run/router/history.ts","../node_modules/@remix-run/router/utils.ts","../node_modules/@remix-run/router/router.ts","../node_modules/react-router/lib/context.ts","../node_modules/react-router/lib/hooks.tsx","../node_modules/react-router/lib/components.tsx","../node_modules/react-router/index.ts","../node_modules/react-router-dom/dom.ts","../node_modules/react-router-dom/index.tsx","../node_modules/wagmi/src/hydrate.ts","../node_modules/@wagmi/core/src/hydrate.ts","../node_modules/wagmi/src/context.ts","../node_modules/viem/chains/definitions/arbitrum.ts","../node_modules/viem/chains/definitions/polygon.ts","../node_modules/viem/op-stack/formatters.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/experimental/eip7702/utils/serializeAuthorizationList.ts","../node_modules/viem/op-stack/serializers.ts","../node_modules/viem/op-stack/chainConfig.ts","../node_modules/viem/op-stack/contracts.ts","../node_modules/viem/chains/definitions/optimism.ts","../node_modules/viem/chains/definitions/base.ts","../node_modules/viem/zksync/constants/number.ts","../node_modules/viem/zksync/formatters.ts","../node_modules/viem/zksync/errors/transaction.ts","../node_modules/viem/zksync/utils/isEip712Transaction.ts","../node_modules/viem/zksync/utils/assertEip712Transaction.ts","../node_modules/viem/zksync/serializers.ts","../node_modules/viem/zksync/errors/bytecode.ts","../node_modules/viem/zksync/chainConfig.ts","../node_modules/viem/zksync/utils/getEip712Domain.ts","../node_modules/viem/zksync/utils/hashBytecode.ts","../node_modules/viem/chains/definitions/zksync.ts","../node_modules/viem/celo/fees.ts","../node_modules/viem/celo/utils.ts","../node_modules/viem/celo/serializers.ts","../node_modules/viem/celo/chainConfig.ts","../node_modules/viem/chains/definitions/celo.ts","../node_modules/viem/celo/formatters.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/assertClassBrand.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet2.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet2.js","../node_modules/@tanstack/query-core/src/utils.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js","../node_modules/@tanstack/query-core/src/notifyManager.ts","../node_modules/@tanstack/query-core/src/subscribable.ts","../node_modules/@tanstack/query-core/src/focusManager.ts","../node_modules/@tanstack/query-core/src/onlineManager.ts","../node_modules/@tanstack/query-core/src/retryer.ts","../node_modules/@tanstack/query-core/src/removable.ts","../node_modules/@tanstack/query-core/src/query.ts","../node_modules/@tanstack/query-core/src/queryCache.ts","../node_modules/@tanstack/query-core/src/mutation.ts","../node_modules/@tanstack/query-core/src/mutationCache.ts","../node_modules/@tanstack/query-core/src/infiniteQueryBehavior.ts","../node_modules/@tanstack/query-core/src/queryClient.ts","../node_modules/@tanstack/react-query/src/QueryClientProvider.tsx","theme.ts","../node_modules/wagmi/src/errors/base.ts","../node_modules/wagmi/src/utils/getVersion.ts","../node_modules/wagmi/src/version.ts","../node_modules/wagmi/src/errors/context.ts","../node_modules/wagmi/src/hooks/useConfig.ts","../node_modules/wagmi/src/hooks/useSyncExternalStoreWithTracked.ts","../node_modules/wagmi/src/hooks/useAccount.ts","assets/logo.svg","../node_modules/react-spinners/esm/helpers/unitConverter.js","../node_modules/react-spinners/esm/helpers/animation.js","../node_modules/react-spinners/esm/ClipLoader.js","hooks/useWindowProps.ts","components/Spacer.tsx","components/Button.tsx","components/ConnectWallet.tsx","../node_modules/@tanstack/query-core/src/mutationObserver.ts","../node_modules/@tanstack/react-query/src/utils.ts","../node_modules/@tanstack/react-query/src/useMutation.ts","../node_modules/wagmi/src/hooks/useConnections.ts","../node_modules/@wagmi/core/src/actions/watchConnections.ts","../node_modules/wagmi/src/hooks/useDisconnect.ts","../node_modules/@wagmi/core/src/query/disconnect.ts","../node_modules/@wagmi/core/src/actions/getChains.ts","../node_modules/wagmi/src/hooks/useChains.ts","../node_modules/@wagmi/core/src/actions/watchChains.ts","../node_modules/wagmi/src/hooks/useSwitchChain.ts","../node_modules/@wagmi/core/src/query/switchChain.ts","../node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs","../node_modules/framer-motion/dist/es/context/MotionContext/index.mjs","../node_modules/framer-motion/dist/es/context/PresenceContext.mjs","../node_modules/framer-motion/dist/es/utils/is-browser.mjs","../node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs","../node_modules/framer-motion/dist/es/context/LazyContext.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs","../node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs","../node_modules/framer-motion/dist/es/utils/is-ref-object.mjs","../node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs","../node_modules/framer-motion/dist/es/render/utils/variant-props.mjs","../node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs","../node_modules/framer-motion/dist/es/context/MotionContext/create.mjs","../node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs","../node_modules/framer-motion/dist/es/motion/features/definitions.mjs","../node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs","../node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs","../node_modules/framer-motion/dist/es/motion/utils/symbol.mjs","../node_modules/framer-motion/dist/es/motion/index.mjs","../node_modules/framer-motion/dist/es/motion/features/load-features.mjs","../node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs","../node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs","../node_modules/framer-motion/dist/es/render/dom/motion-proxy.mjs","../node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs","../node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs","../node_modules/framer-motion/dist/es/render/html/utils/transform.mjs","../node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs","../node_modules/framer-motion/dist/es/value/utils/is-motion-value.mjs","../node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/is-css-variable.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/get-as-type.mjs","../node_modules/framer-motion/dist/es/utils/clamp.mjs","../node_modules/framer-motion/dist/es/value/types/numbers/index.mjs","../node_modules/framer-motion/dist/es/value/types/utils.mjs","../node_modules/framer-motion/dist/es/value/types/numbers/units.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/type-int.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/number.mjs","../node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs","../node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs","../node_modules/framer-motion/dist/es/render/html/use-props.mjs","../node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/transform-origin.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/path.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs","../node_modules/framer-motion/dist/es/render/svg/use-props.mjs","../node_modules/framer-motion/dist/es/render/dom/use-render.mjs","../node_modules/framer-motion/dist/es/render/html/utils/render.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/render.mjs","../node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs","../node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs","../node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs","../node_modules/framer-motion/dist/es/utils/resolve-value.mjs","../node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs","../node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs","../node_modules/framer-motion/dist/es/utils/use-constant.mjs","../node_modules/framer-motion/dist/es/utils/noop.mjs","../node_modules/framer-motion/dist/es/frameloop/render-step.mjs","../node_modules/framer-motion/dist/es/frameloop/batcher.mjs","../node_modules/framer-motion/dist/es/frameloop/frame.mjs","../node_modules/framer-motion/dist/es/render/svg/config-motion.mjs","../node_modules/framer-motion/dist/es/render/html/config-motion.mjs","../node_modules/framer-motion/dist/es/events/add-dom-event.mjs","../node_modules/framer-motion/dist/es/events/utils/is-primary-pointer.mjs","../node_modules/framer-motion/dist/es/events/event-info.mjs","../node_modules/framer-motion/dist/es/events/add-pointer-event.mjs","../node_modules/framer-motion/dist/es/utils/pipe.mjs","../node_modules/framer-motion/dist/es/gestures/drag/utils/lock.mjs","../node_modules/framer-motion/dist/es/motion/features/Feature.mjs","../node_modules/framer-motion/dist/es/gestures/hover.mjs","../node_modules/framer-motion/dist/es/gestures/utils/is-node-or-child.mjs","../node_modules/framer-motion/dist/es/gestures/press.mjs","../node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs","../node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs","../node_modules/framer-motion/dist/es/motion/features/gestures.mjs","../node_modules/framer-motion/dist/es/gestures/focus.mjs","../node_modules/framer-motion/dist/es/utils/shallow-compare.mjs","../node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs","../node_modules/framer-motion/dist/es/utils/errors.mjs","../node_modules/framer-motion/dist/es/utils/time-conversion.mjs","../node_modules/framer-motion/dist/es/utils/use-instant-transition-state.mjs","../node_modules/framer-motion/dist/es/easing/utils/is-bezier-definition.mjs","../node_modules/framer-motion/dist/es/animation/animators/waapi/easing.mjs","../node_modules/framer-motion/dist/es/easing/cubic-bezier.mjs","../node_modules/framer-motion/dist/es/easing/ease.mjs","../node_modules/framer-motion/dist/es/easing/utils/is-easing-array.mjs","../node_modules/framer-motion/dist/es/easing/modifiers/mirror.mjs","../node_modules/framer-motion/dist/es/easing/modifiers/reverse.mjs","../node_modules/framer-motion/dist/es/easing/circ.mjs","../node_modules/framer-motion/dist/es/easing/back.mjs","../node_modules/framer-motion/dist/es/easing/utils/map.mjs","../node_modules/framer-motion/dist/es/easing/anticipate.mjs","../node_modules/framer-motion/dist/es/value/types/color/utils.mjs","../node_modules/framer-motion/dist/es/value/types/color/rgba.mjs","../node_modules/framer-motion/dist/es/value/types/color/hex.mjs","../node_modules/framer-motion/dist/es/value/types/color/hsla.mjs","../node_modules/framer-motion/dist/es/value/types/color/index.mjs","../node_modules/framer-motion/dist/es/utils/mix.mjs","../node_modules/framer-motion/dist/es/utils/hsla-to-rgba.mjs","../node_modules/framer-motion/dist/es/utils/mix-color.mjs","../node_modules/framer-motion/dist/es/value/types/complex/index.mjs","../node_modules/framer-motion/dist/es/utils/mix-complex.mjs","../node_modules/framer-motion/dist/es/utils/progress.mjs","../node_modules/framer-motion/dist/es/utils/interpolate.mjs","../node_modules/framer-motion/dist/es/utils/offsets/default.mjs","../node_modules/framer-motion/dist/es/utils/offsets/fill.mjs","../node_modules/framer-motion/dist/es/animation/generators/keyframes.mjs","../node_modules/framer-motion/dist/es/utils/offsets/time.mjs","../node_modules/framer-motion/dist/es/utils/velocity-per-second.mjs","../node_modules/framer-motion/dist/es/animation/generators/utils/velocity.mjs","../node_modules/framer-motion/dist/es/animation/generators/spring/find.mjs","../node_modules/framer-motion/dist/es/animation/generators/spring/index.mjs","../node_modules/framer-motion/dist/es/animation/generators/inertia.mjs","../node_modules/framer-motion/dist/es/animation/animators/js/driver-frameloop.mjs","../node_modules/framer-motion/dist/es/animation/generators/utils/calc-duration.mjs","../node_modules/framer-motion/dist/es/animation/animators/js/index.mjs","../node_modules/framer-motion/dist/es/animation/animators/waapi/create-accelerated-animation.mjs","../node_modules/framer-motion/dist/es/utils/memo.mjs","../node_modules/framer-motion/dist/es/animation/animators/waapi/index.mjs","../node_modules/framer-motion/dist/es/animation/animators/waapi/utils/get-final-keyframe.mjs","../node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-animatable.mjs","../node_modules/framer-motion/dist/es/value/types/complex/filter.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/defaults.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/animatable-none.mjs","../node_modules/framer-motion/dist/es/utils/is-zero-value-string.mjs","../node_modules/framer-motion/dist/es/animation/utils/is-none.mjs","../node_modules/framer-motion/dist/es/animation/utils/transitions.mjs","../node_modules/framer-motion/dist/es/utils/GlobalConfig.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs","../node_modules/framer-motion/dist/es/animation/utils/keyframes.mjs","../node_modules/framer-motion/dist/es/animation/animators/instant.mjs","../node_modules/framer-motion/dist/es/value/use-will-change/is.mjs","../node_modules/framer-motion/dist/es/utils/is-numerical-string.mjs","../node_modules/framer-motion/dist/es/utils/array.mjs","../node_modules/framer-motion/dist/es/utils/subscription-manager.mjs","../node_modules/framer-motion/dist/es/value/index.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/test.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/dimensions.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/type-auto.mjs","../node_modules/framer-motion/dist/es/render/dom/value-types/find.mjs","../node_modules/framer-motion/dist/es/render/utils/setters.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/visual-element-target.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/visual-element-variant.mjs","../node_modules/framer-motion/dist/es/render/utils/animation-state.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/visual-element.mjs","../node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs","../node_modules/framer-motion/dist/es/motion/features/animations.mjs","../node_modules/framer-motion/dist/es/motion/features/animation/index.mjs","../node_modules/framer-motion/dist/es/utils/distance.mjs","../node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs","../node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs","../node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs","../node_modules/framer-motion/dist/es/projection/geometry/models.mjs","../node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs","../node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs","../node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs","../node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs","../node_modules/framer-motion/dist/es/projection/utils/measure.mjs","../node_modules/framer-motion/dist/es/utils/get-context-window.mjs","../node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs","../node_modules/framer-motion/dist/es/gestures/pan/index.mjs","../node_modules/framer-motion/dist/es/projection/node/state.mjs","../node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs","../node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs","../node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs","../node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs","../node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs","../node_modules/framer-motion/dist/es/projection/geometry/copy.mjs","../node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs","../node_modules/framer-motion/dist/es/projection/geometry/utils.mjs","../node_modules/framer-motion/dist/es/projection/shared/stack.mjs","../node_modules/framer-motion/dist/es/projection/styles/transform.mjs","../node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs","../node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs","../node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs","../node_modules/framer-motion/dist/es/debug/record.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/is-svg-element.mjs","../node_modules/framer-motion/dist/es/utils/delay.mjs","../node_modules/framer-motion/dist/es/animation/interfaces/single-value.mjs","../node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs","../node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs","../node_modules/framer-motion/dist/es/motion/features/drag.mjs","../node_modules/framer-motion/dist/es/gestures/drag/index.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/css-variables-conversion.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/unit-conversion.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/parse-dom-variant.mjs","../node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs","../node_modules/framer-motion/dist/es/render/store.mjs","../node_modules/framer-motion/dist/es/render/VisualElement.mjs","../node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs","../node_modules/framer-motion/dist/es/render/utils/motion-values.mjs","../node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs","../node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs","../node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs","../node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs","../node_modules/framer-motion/dist/es/render/dom/motion.mjs","../node_modules/framer-motion/dist/es/motion/features/layout.mjs","../node_modules/framer-motion/dist/es/render/dom/utils/create-config.mjs","components/Modal.tsx","utils/address.ts","abi/ccip-router.ts","data/networks.ts","components/ChainSelectorModal.tsx","components/WalletConnectionManager.tsx","sections/Topbar.tsx","components/Title.tsx","components/Subtitle.tsx","../node_modules/wagmi/src/hooks/useWriteContract.ts","../node_modules/@wagmi/core/src/query/writeContract.ts","../node_modules/@wagmi/core/src/query/utils.ts","../node_modules/@wagmi/core/src/query/waitForTransactionReceipt.ts","../node_modules/@tanstack/query-core/src/queryObserver.ts","../node_modules/@tanstack/react-query/src/QueryErrorResetBoundary.tsx","../node_modules/@tanstack/react-query/src/isRestoring.ts","../node_modules/@tanstack/react-query/src/errorBoundaryUtils.ts","../node_modules/@tanstack/react-query/src/suspense.ts","../node_modules/@tanstack/react-query/src/useQuery.ts","../node_modules/@tanstack/react-query/src/useBaseQuery.ts","../node_modules/wagmi/src/utils/query.ts","../node_modules/@wagmi/core/src/actions/getChainId.ts","../node_modules/wagmi/src/hooks/useChainId.ts","../node_modules/@wagmi/core/src/actions/watchChainId.ts","../node_modules/wagmi/src/hooks/useWaitForTransactionReceipt.ts","../node_modules/@wagmi/core/src/query/readContract.ts","../node_modules/wagmi/src/hooks/useReadContract.ts","../node_modules/ethers/src.ts/_version.ts","../node_modules/ethers/src.ts/utils/properties.ts","../node_modules/ethers/src.ts/utils/errors.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/defineProperty.js","../node_modules/ethers/src.ts/utils/data.ts","../node_modules/ethers/src.ts/utils/maths.ts","../node_modules/ethers/src.ts/utils/fixednumber.ts","../node_modules/ethers/src.ts/utils/units.ts","components/Card.tsx","assets/wrapLogo.svg","components/CryptoInput.tsx","assets/usdm.svg","assets/wusdm.svg","../node_modules/lucide-react/src/defaultAttributes.ts","../node_modules/lucide-react/src/createLucideIcon.ts","../node_modules/lucide-react/src/icons/external-link.ts","components/LinkToast.tsx","abi/usdm.ts","abi/wusdm.ts","sections/WrapUnwrap.tsx","components/FAQs.tsx","data/wrapFaqs.ts","hooks/usePageViewSend.ts","../node_modules/react-helmet/es/Helmet.js","components/Head.tsx","screens/WrapScreen.tsx","../node_modules/lucide-react/src/icons/chevron-down.ts","../node_modules/axios/lib/helpers/bind.js","../node_modules/axios/lib/utils.js","../node_modules/axios/lib/core/AxiosError.js","../node_modules/axios/lib/helpers/toFormData.js","../node_modules/axios/lib/helpers/AxiosURLSearchParams.js","../node_modules/axios/lib/helpers/buildURL.js","../node_modules/axios/lib/core/InterceptorManager.js","../node_modules/axios/lib/defaults/transitional.js","../node_modules/axios/lib/platform/browser/index.js","../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js","../node_modules/axios/lib/platform/browser/classes/FormData.js","../node_modules/axios/lib/platform/browser/classes/Blob.js","../node_modules/axios/lib/platform/common/utils.js","../node_modules/axios/lib/platform/index.js","../node_modules/axios/lib/helpers/formDataToJSON.js","../node_modules/axios/lib/defaults/index.js","../node_modules/axios/lib/helpers/toURLEncodedForm.js","../node_modules/axios/lib/helpers/parseHeaders.js","../node_modules/axios/lib/core/AxiosHeaders.js","../node_modules/axios/lib/core/transformData.js","../node_modules/axios/lib/cancel/isCancel.js","../node_modules/axios/lib/cancel/CanceledError.js","../node_modules/axios/lib/core/settle.js","../node_modules/axios/lib/helpers/speedometer.js","../node_modules/axios/lib/helpers/throttle.js","../node_modules/axios/lib/helpers/progressEventReducer.js","../node_modules/axios/lib/helpers/isURLSameOrigin.js","../node_modules/axios/lib/helpers/cookies.js","../node_modules/axios/lib/core/buildFullPath.js","../node_modules/axios/lib/helpers/isAbsoluteURL.js","../node_modules/axios/lib/helpers/combineURLs.js","../node_modules/axios/lib/core/mergeConfig.js","../node_modules/axios/lib/helpers/resolveConfig.js","../node_modules/axios/lib/adapters/xhr.js","../node_modules/axios/lib/helpers/parseProtocol.js","../node_modules/axios/lib/helpers/composeSignals.js","../node_modules/axios/lib/helpers/trackStream.js","../node_modules/axios/lib/adapters/fetch.js","../node_modules/axios/lib/adapters/adapters.js","../node_modules/axios/lib/helpers/null.js","../node_modules/axios/lib/core/dispatchRequest.js","../node_modules/axios/lib/env/data.js","../node_modules/axios/lib/helpers/validator.js","../node_modules/axios/lib/core/Axios.js","../node_modules/axios/lib/cancel/CancelToken.js","../node_modules/axios/lib/helpers/HttpStatusCode.js","../node_modules/axios/lib/axios.js","../node_modules/axios/lib/helpers/spread.js","../node_modules/axios/lib/helpers/isAxiosError.js","api/useCurvePools.ts","assets/arbitrum.svg","assets/eth.svg","assets/base.svg","assets/optimism.svg","assets/matic.svg","api/useCurveApys.ts","../node_modules/zustand/esm/vanilla.mjs","../node_modules/zustand/esm/index.mjs","state/useInternalUseStore.ts","sections/LiquidityOptions.tsx","data/liquidityFaqs.ts","screens/LiquidityScreen.tsx","../node_modules/lucide-react/src/icons/send.ts","../node_modules/ethers/node_modules/@noble/hashes/src/_assert.ts","../node_modules/ethers/node_modules/@noble/hashes/src/_u64.ts","../node_modules/ethers/node_modules/@noble/hashes/src/utils.ts","../node_modules/ethers/node_modules/@noble/hashes/src/sha3.ts","../node_modules/ethers/src.ts/crypto/keccak.ts","../node_modules/ethers/src.ts/utils/utf8.ts","../node_modules/ethers/src.ts/hash/id.ts","../node_modules/ethers/src.ts/abi/coders/abstract-coder.ts","../node_modules/ethers/src.ts/address/address.ts","../node_modules/ethers/src.ts/abi/typed.ts","../node_modules/ethers/src.ts/abi/coders/address.ts","../node_modules/ethers/src.ts/abi/coders/anonymous.ts","../node_modules/ethers/src.ts/abi/coders/array.ts","../node_modules/ethers/src.ts/abi/coders/boolean.ts","../node_modules/ethers/src.ts/abi/coders/bytes.ts","../node_modules/ethers/src.ts/abi/coders/fixed-bytes.ts","../node_modules/ethers/src.ts/abi/coders/null.ts","../node_modules/ethers/src.ts/abi/coders/number.ts","../node_modules/ethers/src.ts/abi/coders/string.ts","../node_modules/ethers/src.ts/abi/coders/tuple.ts","../node_modules/ethers/src.ts/abi/fragments.ts","../node_modules/ethers/src.ts/abi/abi-coder.ts","../node_modules/ethers/src.ts/constants/addresses.ts","components/CardIcon.tsx","components/ChainSelector.tsx","api/useChainlinkMessageId.ts","components/LastTransaction.tsx","assets/chainlink.svg","components/BridgeFee.tsx","sections/Bridge.tsx","data/bridgeFaqs.ts","screens/BridgeScreen.tsx","../node_modules/@lifi/widget/node_modules/react-router-dom/node_modules/@remix-run/router/history.ts","../node_modules/@lifi/widget/node_modules/react-router-dom/node_modules/@remix-run/router/utils.ts","../node_modules/@lifi/widget/node_modules/react-router-dom/node_modules/@remix-run/router/router.ts","../node_modules/@lifi/widget/node_modules/react-router-dom/node_modules/react-router/lib/context.ts","../node_modules/@lifi/widget/node_modules/react-router-dom/node_modules/react-router/lib/hooks.tsx","../node_modules/@lifi/widget/node_modules/react-router-dom/node_modules/react-router/lib/components.tsx","../node_modules/@mui/utils/esm/composeClasses/composeClasses.js","../node_modules/@mui/material/utils/capitalize.js","../node_modules/@mui/utils/esm/resolveProps/resolveProps.js","../node_modules/@mui/system/esm/DefaultPropsProvider/DefaultPropsProvider.js","../node_modules/@mui/material/DefaultPropsProvider/DefaultPropsProvider.js","../node_modules/@mui/material/styles/createMixins.js","../node_modules/@mui/material/colors/common.js","../node_modules/@mui/material/colors/grey.js","../node_modules/@mui/material/colors/purple.js","../node_modules/@mui/material/colors/red.js","../node_modules/@mui/material/colors/orange.js","../node_modules/@mui/material/colors/blue.js","../node_modules/@mui/material/colors/lightBlue.js","../node_modules/@mui/material/colors/green.js","../node_modules/@mui/material/styles/createPalette.js","../node_modules/@mui/material/styles/createTypography.js","../node_modules/@mui/material/styles/shadows.js","../node_modules/@mui/material/styles/createTransitions.js","../node_modules/@mui/material/styles/zIndex.js","../node_modules/@mui/material/styles/createTheme.js","../node_modules/@mui/material/styles/defaultTheme.js","../node_modules/@mui/material/styles/identifier.js","../node_modules/@mui/material/styles/slotShouldForwardProp.js","../node_modules/@mui/material/styles/rootShouldForwardProp.js","../node_modules/@mui/material/styles/styled.js","../node_modules/@mui/utils/esm/ClassNameGenerator/ClassNameGenerator.js","../node_modules/@mui/utils/esm/generateUtilityClass/generateUtilityClass.js","../node_modules/@mui/utils/esm/generateUtilityClasses/generateUtilityClasses.js","../node_modules/@mui/material/SvgIcon/svgIconClasses.js","../node_modules/@mui/material/SvgIcon/SvgIcon.js","../node_modules/@mui/material/utils/createSvgIcon.js","../node_modules/@mui/icons-material/esm/Block.js","../node_modules/@mui/system/esm/useThemeWithoutDefault.js","../node_modules/@mui/system/esm/useTheme.js","../node_modules/@mui/system/esm/createBox.js","../node_modules/@mui/material/Box/boxClasses.js","../node_modules/@mui/material/Box/Box.js","../node_modules/@mui/material/Typography/typographyClasses.js","../node_modules/@mui/material/Typography/Typography.js","../node_modules/html-parse-stringify/src/parse-tag.js","../node_modules/html-parse-stringify/src/parse.js","../node_modules/html-parse-stringify/src/stringify.js","../node_modules/html-parse-stringify/src/index.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/utils.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/unescape.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/defaults.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/i18nInstance.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/TransWithoutContext.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/initReactI18next.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/context.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/Trans.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/useTranslation.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/I18nextProvider.js","../node_modules/@lifi/widget/node_modules/react-i18next/dist/es/useSSR.js","../node_modules/@lifi/widget/components/NotFound.tsx","../node_modules/@mui/icons-material/esm/DeleteOutline.js","../node_modules/@mui/material/styles/useTheme.js","../node_modules/@mui/utils/esm/setRef/setRef.js","../node_modules/@mui/utils/esm/useForkRef/useForkRef.js","../node_modules/@mui/material/utils/useForkRef.js","../node_modules/@mui/utils/esm/useEnhancedEffect/useEnhancedEffect.js","../node_modules/@mui/utils/esm/useEventCallback/useEventCallback.js","../node_modules/@mui/material/utils/useEventCallback.js","../node_modules/@mui/utils/esm/useLazyRef/useLazyRef.js","../node_modules/@mui/utils/esm/useOnMount/useOnMount.js","../node_modules/@mui/utils/esm/useTimeout/useTimeout.js","../node_modules/@mui/utils/esm/useIsFocusVisible/useIsFocusVisible.js","../node_modules/@mui/material/utils/useIsFocusVisible.js","../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../node_modules/react-transition-group/esm/TransitionGroupContext.js","../node_modules/react-transition-group/esm/utils/ChildMapping.js","../node_modules/react-transition-group/esm/TransitionGroup.js","../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../node_modules/@mui/material/ButtonBase/Ripple.js","../node_modules/@mui/material/ButtonBase/touchRippleClasses.js","../node_modules/@mui/material/ButtonBase/TouchRipple.js","../node_modules/@mui/material/ButtonBase/buttonBaseClasses.js","../node_modules/@mui/material/ButtonBase/ButtonBase.js","../node_modules/@mui/material/IconButton/iconButtonClasses.js","../node_modules/@mui/material/IconButton/IconButton.js","../node_modules/@mui/material/List/ListContext.js","../node_modules/@mui/material/List/listClasses.js","../node_modules/@mui/material/List/List.js","../node_modules/@mui/material/DialogTitle/dialogTitleClasses.js","../node_modules/@mui/material/Dialog/DialogContext.js","../node_modules/@mui/material/DialogTitle/DialogTitle.js","../node_modules/@mui/material/DialogContent/dialogContentClasses.js","../node_modules/@mui/material/DialogContent/DialogContent.js","../node_modules/@mui/material/DialogContentText/dialogContentTextClasses.js","../node_modules/@mui/material/DialogContentText/DialogContentText.js","../node_modules/@mui/material/DialogActions/dialogActionsClasses.js","../node_modules/@mui/material/DialogActions/DialogActions.js","../node_modules/@mui/material/Button/buttonClasses.js","../node_modules/@mui/material/ButtonGroup/ButtonGroupContext.js","../node_modules/@mui/material/ButtonGroup/ButtonGroupButtonContext.js","../node_modules/@mui/material/Button/Button.js","../node_modules/@mui/icons-material/esm/InfoRounded.js","../node_modules/@mui/icons-material/esm/ErrorRounded.js","../node_modules/@mui/icons-material/esm/ArrowForward.js","../node_modules/@mui/material/ListItemAvatar/listItemAvatarClasses.js","../node_modules/@mui/material/ListItemAvatar/ListItemAvatar.js","../node_modules/@mui/material/ListItemText/listItemTextClasses.js","../node_modules/@mui/material/ListItemText/ListItemText.js","../node_modules/@lifi/sdk/src/errors/constants.ts","../node_modules/@lifi/types/src/chains/Chain.ts","../node_modules/@lifi/sdk/src/config.ts","../node_modules/@lifi/types/src/api.ts","../node_modules/@lifi/sdk/src/errors/baseError.ts","../node_modules/@lifi/sdk/src/errors/utils/rootCause.ts","../node_modules/@lifi/sdk/src/errors/errors.ts","../node_modules/@lifi/sdk/src/version.ts","../node_modules/@lifi/sdk/src/errors/SDKError.ts","../node_modules/@lifi/sdk/src/errors/httpError.ts","../node_modules/@lifi/sdk/src/constants.ts","../node_modules/@lifi/sdk/src/utils/utils.ts","../node_modules/@lifi/sdk/src/request.ts","../node_modules/@lifi/sdk/src/typeguards.ts","../node_modules/@lifi/sdk/src/services/api.ts","../node_modules/@lifi/sdk/src/createConfig.ts","../node_modules/@lifi/widget/config/version.ts","../node_modules/@lifi/widget/node_modules/zustand/esm/middleware.mjs","../node_modules/@lifi/widget/node_modules/zustand/esm/vanilla.mjs","../node_modules/@lifi/widget/node_modules/zustand/esm/traditional.mjs","../node_modules/@lifi/widget/stores/settings/types.ts","../node_modules/@lifi/widget/stores/settings/useSettingsStore.ts","../node_modules/@lifi/widget/providers/WidgetProvider/WidgetProvider.tsx","../node_modules/@lifi/widget/node_modules/viem/utils/unit/formatUnits.ts","../node_modules/@lifi/widget/utils/format.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/subscribable.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/utils.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/focusManager.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/notifyManager.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/onlineManager.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/thenable.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/retryer.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/removable.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/query.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/queryObserver.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/QueryClientProvider.tsx","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/QueryErrorResetBoundary.tsx","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/utils.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/errorBoundaryUtils.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/isRestoring.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/suspense.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/useQuery.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/useBaseQuery.ts","../node_modules/@lifi/widget/providers/WalletProvider/EVMExternalContext.ts","../node_modules/@lifi/widget/providers/WalletProvider/SVMExternalContext.ts","../node_modules/@lifi/widget/providers/WalletProvider/useHasExternalWalletProvider.ts","../node_modules/@lifi/widget/utils/item.ts","../node_modules/@lifi/widget/hooks/useAvailableChains.ts","../node_modules/@lifi/widget/hooks/useProcessMessage.ts","../node_modules/@lifi/sdk/src/core/executionState.ts","../node_modules/@lifi/sdk/src/core/prepareRestart.ts","../node_modules/@lifi/sdk/src/core/execution.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/mutation.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/mutationObserver.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/useMutation.ts","../node_modules/@lifi/widget/node_modules/zustand/esm/shallow.mjs","../node_modules/@lifi/widget/utils/enum.ts","../node_modules/@lifi/widget/stores/routes/types.ts","../node_modules/microdiff/dist/index.js","../node_modules/@lifi/widget/stores/routes/utils.ts","../node_modules/@lifi/widget/stores/routes/createRouteExecutionStore.ts","../node_modules/@lifi/widget/stores/routes/RouteExecutionStore.tsx","../node_modules/@lifi/widget/types/events.ts","../node_modules/@lifi/types/src/chains/base.ts","../node_modules/@solana/wallet-adapter-react/src/useWallet.ts","../node_modules/@lifi/widget/hooks/useAccount.ts","../node_modules/@lifi/widget/hooks/useWidgetEvents.ts","../node_modules/mitt/src/index.ts","../node_modules/@lifi/widget/hooks/useRouteExecution.ts","../node_modules/@lifi/widget/utils/navigationRoutes.ts","../node_modules/@mui/material/internal/svg-icons/Person.js","../node_modules/@mui/material/Avatar/avatarClasses.js","../node_modules/@mui/utils/esm/isHostComponent/isHostComponent.js","../node_modules/@mui/utils/esm/appendOwnerState/appendOwnerState.js","../node_modules/@mui/utils/esm/resolveComponentProps/resolveComponentProps.js","../node_modules/@mui/utils/esm/extractEventHandlers/extractEventHandlers.js","../node_modules/@mui/utils/esm/omitEventHandlers/omitEventHandlers.js","../node_modules/@mui/utils/esm/mergeSlotProps/mergeSlotProps.js","../node_modules/@mui/material/utils/useSlot.js","../node_modules/@mui/material/Avatar/Avatar.js","../node_modules/@mui/material/styles/cssUtils.js","../node_modules/@mui/system/esm/colorManipulator.js","../node_modules/@mui/material/Skeleton/skeletonClasses.js","../node_modules/@mui/material/Skeleton/Skeleton.js","../node_modules/@mui/material/AvatarGroup/avatarGroupClasses.js","../node_modules/@mui/material/AvatarGroup/AvatarGroup.js","../node_modules/@mui/material/Badge/badgeClasses.js","../node_modules/@lifi/widget/components/Avatar/utils.ts","../node_modules/@lifi/widget/components/Avatar/Avatar.style.tsx","../node_modules/@mui/utils/esm/usePreviousProps/usePreviousProps.js","../node_modules/@mui/utils/esm/useSlotProps/useSlotProps.js","../node_modules/@mui/material/Badge/useBadge.js","../node_modules/@mui/material/Badge/Badge.js","../node_modules/@lifi/widget/hooks/useChain.ts","../node_modules/@lifi/widget/hooks/useTokenSearch.ts","../node_modules/@lifi/widget/hooks/useChains.ts","../node_modules/@lifi/widget/hooks/useTokens.ts","../node_modules/@lifi/widget/hooks/useToken.ts","../node_modules/@lifi/widget/components/SmallAvatar.tsx","../node_modules/@lifi/widget/components/Avatar/Avatar.tsx","../node_modules/@lifi/widget/components/Avatar/TokenAvatar.tsx","../node_modules/@mui/icons-material/esm/AccessTimeFilled.js","../node_modules/@mui/system/esm/RtlProvider/index.js","../node_modules/react-transition-group/esm/config.js","../node_modules/react-transition-group/esm/utils/reflow.js","../node_modules/react-transition-group/esm/Transition.js","../node_modules/@mui/material/transitions/utils.js","../node_modules/@mui/material/Grow/Grow.js","../node_modules/@mui/utils/esm/ownerDocument/ownerDocument.js","../node_modules/@popperjs/core/lib/dom-utils/getWindow.js","../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","../node_modules/@popperjs/core/lib/utils/math.js","../node_modules/@popperjs/core/lib/utils/userAgent.js","../node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","../node_modules/@popperjs/core/lib/enums.js","../node_modules/@popperjs/core/lib/utils/orderModifiers.js","../node_modules/@popperjs/core/lib/utils/debounce.js","../node_modules/@popperjs/core/lib/createPopper.js","../node_modules/@popperjs/core/lib/utils/mergeByName.js","../node_modules/@popperjs/core/lib/modifiers/eventListeners.js","../node_modules/@popperjs/core/lib/utils/getBasePlacement.js","../node_modules/@popperjs/core/lib/utils/getVariation.js","../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","../node_modules/@popperjs/core/lib/utils/computeOffsets.js","../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","../node_modules/@popperjs/core/lib/modifiers/computeStyles.js","../node_modules/@popperjs/core/lib/modifiers/applyStyles.js","../node_modules/@popperjs/core/lib/modifiers/offset.js","../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","../node_modules/@popperjs/core/lib/dom-utils/contains.js","../node_modules/@popperjs/core/lib/utils/rectToClientRect.js","../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","../node_modules/@popperjs/core/lib/utils/expandToHashMap.js","../node_modules/@popperjs/core/lib/utils/detectOverflow.js","../node_modules/@popperjs/core/lib/modifiers/flip.js","../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","../node_modules/@popperjs/core/lib/utils/within.js","../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","../node_modules/@popperjs/core/lib/utils/getAltAxis.js","../node_modules/@popperjs/core/lib/modifiers/arrow.js","../node_modules/@popperjs/core/lib/modifiers/hide.js","../node_modules/@popperjs/core/lib/popper.js","../node_modules/@mui/material/Portal/Portal.js","../node_modules/@mui/material/Popper/popperClasses.js","../node_modules/@mui/material/Popper/BasePopper.js","../node_modules/@mui/material/Popper/Popper.js","../node_modules/@mui/utils/esm/useId/useId.js","../node_modules/@mui/material/utils/useId.js","../node_modules/@mui/material/utils/useControlled.js","../node_modules/@mui/utils/esm/useControlled/useControlled.js","../node_modules/@mui/material/Tooltip/tooltipClasses.js","../node_modules/@mui/material/Tooltip/Tooltip.js","../node_modules/@lifi/widget/hooks/timer/utils.ts","../node_modules/@lifi/widget/hooks/timer/useTimer.ts","../node_modules/@lifi/widget/hooks/timer/useInterval.ts","../node_modules/@lifi/widget/components/IconTypography.ts","../node_modules/@lifi/widget/components/Step/StepTimer.tsx","../node_modules/@mui/material/utils/useEnhancedEffect.js","../node_modules/@mui/material/ListItemButton/listItemButtonClasses.js","../node_modules/@mui/material/ListItemButton/ListItemButton.js","../node_modules/@mui/material/utils/isMuiElement.js","../node_modules/@mui/utils/esm/isMuiElement/isMuiElement.js","../node_modules/@mui/material/ListItem/listItemClasses.js","../node_modules/@mui/material/ListItemSecondaryAction/listItemSecondaryActionClasses.js","../node_modules/@mui/material/ListItemSecondaryAction/ListItemSecondaryAction.js","../node_modules/@mui/material/ListItem/ListItem.js","../node_modules/@lifi/widget/utils/colors.ts","../node_modules/@lifi/widget/components/ActiveTransactions/ActiveTransactions.style.ts","../node_modules/@lifi/widget/components/ActiveTransactions/ActiveTransactionItem.tsx","../node_modules/@mui/material/Unstable_TrapFocus/FocusTrap.js","../node_modules/@mui/material/Fade/Fade.js","../node_modules/@mui/material/Backdrop/backdropClasses.js","../node_modules/@mui/material/Backdrop/Backdrop.js","../node_modules/@mui/utils/esm/createChainedFunction/createChainedFunction.js","../node_modules/@mui/utils/esm/ownerWindow/ownerWindow.js","../node_modules/@mui/utils/esm/getScrollbarSize/getScrollbarSize.js","../node_modules/@mui/material/Modal/ModalManager.js","../node_modules/@mui/material/Modal/useModal.js","../node_modules/@mui/material/Modal/modalClasses.js","../node_modules/@mui/material/Modal/Modal.js","../node_modules/@mui/material/styles/getOverlayAlpha.js","../node_modules/@mui/material/Paper/paperClasses.js","../node_modules/@mui/material/Paper/Paper.js","../node_modules/@mui/material/Dialog/dialogClasses.js","../node_modules/@mui/material/Dialog/Dialog.js","../node_modules/@lifi/widget/utils/elements.ts","../node_modules/@lifi/widget/hooks/useDefaultElementId.ts","../node_modules/@lifi/widget/hooks/useScrollableContainer.ts","../node_modules/@lifi/widget/components/Dialog.tsx","../node_modules/@mui/system/esm/useThemeProps/getThemeProps.js","../node_modules/@mui/system/esm/useThemeProps/useThemeProps.js","../node_modules/@mui/system/esm/createStyled.js","../node_modules/@mui/system/esm/styled.js","../node_modules/@mui/system/esm/Container/createContainer.js","../node_modules/@mui/material/Container/Container.js","../node_modules/@lifi/widget/components/PageContainer.ts","../node_modules/@lifi/widget/stores/header/useHeaderStore.tsx","../node_modules/@lifi/widget/hooks/useHeader.ts","../node_modules/@lifi/widget/stores/routes/useExecutingRoutesIds.ts","../node_modules/@mui/icons-material/esm/SwapHoriz.js","../node_modules/@lifi/widget/pages/ActiveTransactionsPage/ActiveTransactionsEmpty.tsx","../node_modules/@lifi/widget/pages/ActiveTransactionsPage/ActiveTransactionsPage.tsx","../node_modules/@mui/icons-material/esm/Check.js","../node_modules/@lifi/widget/components/ListItemText.tsx","../node_modules/@lifi/widget/components/ListItemButton.tsx","../node_modules/@lifi/widget/components/SettingsListItemButton.tsx","../node_modules/@lifi/widget/stores/settings/useSettings.ts","../node_modules/@lifi/widget/hooks/useLanguages.ts","../node_modules/@mui/system/esm/Stack/createStack.js","../node_modules/@mui/material/Stack/Stack.js","../node_modules/@mui/material/Card/cardClasses.js","../node_modules/@mui/material/Card/Card.js","../node_modules/@lifi/widget/components/Card/Card.tsx","../node_modules/@lifi/widget/components/Card/CardTitle.tsx","../node_modules/@lifi/widget/components/ActiveTransactions/ActiveTransactions.tsx","../node_modules/@lifi/widget/stores/form/types.ts","../node_modules/@lifi/widget/stores/form/FormStoreContext.ts","../node_modules/@lifi/widget/stores/form/useFormStore.ts","../node_modules/@lifi/widget/stores/form/useFieldActions.ts","../node_modules/@lifi/widget/stores/form/useFieldValues.ts","../node_modules/@lifi/widget/stores/form/useFieldController.ts","../node_modules/@lifi/widget/types/widget.ts","../node_modules/@lifi/widget/utils/input.ts","../node_modules/@lifi/widget/components/Card/InputCard.tsx","../node_modules/@mui/material/InputBase/utils.js","../node_modules/@mui/material/FormControl/FormControlContext.js","../node_modules/@mui/material/FormControl/formControlClasses.js","../node_modules/@mui/material/FormControl/FormControl.js","../node_modules/@mui/utils/esm/debounce/debounce.js","../node_modules/@mui/material/TextareaAutosize/TextareaAutosize.js","../node_modules/@mui/material/FormControl/formControlState.js","../node_modules/@mui/material/FormControl/useFormControl.js","../node_modules/@mui/system/esm/GlobalStyles/GlobalStyles.js","../node_modules/@mui/material/GlobalStyles/GlobalStyles.js","../node_modules/@mui/material/InputBase/inputBaseClasses.js","../node_modules/@mui/material/InputBase/InputBase.js","../node_modules/@lifi/widget/components/AmountInput/AmountInput.style.tsx","../node_modules/@mui/material/InputAdornment/inputAdornmentClasses.js","../node_modules/@mui/material/InputAdornment/InputAdornment.js","../node_modules/@lifi/widget/hooks/useGasRecommendation.ts","../node_modules/@lifi/sdk/src/services/balance.ts","../node_modules/@lifi/widget/hooks/useTokenBalances.ts","../node_modules/@lifi/widget/hooks/useTokenAddressBalance.ts","../node_modules/@lifi/widget/components/AmountInput/AmountInputAdornment.style.tsx","../node_modules/@lifi/widget/components/AmountInput/AmountInputEndAdornment.tsx","../node_modules/@lifi/widget/components/AmountInput/AmountInputStartAdornment.tsx","../node_modules/@mui/material/FormHelperText/formHelperTextClasses.js","../node_modules/@mui/material/FormHelperText/FormHelperText.js","../node_modules/@lifi/widget/components/AmountInput/PriceFormHelperText.tsx","../node_modules/@lifi/widget/components/AmountInput/AmountInput.tsx","../node_modules/@lifi/widget/components/ContractComponent/ContractComponent.tsx","../node_modules/@mui/icons-material/esm/EvStation.js","../node_modules/@mui/material/Collapse/collapseClasses.js","../node_modules/@mui/material/Collapse/Collapse.js","../node_modules/@lifi/widget/hooks/useTokenBalance.ts","../node_modules/@lifi/widget/hooks/useGasRefuel.ts","../node_modules/@lifi/widget/components/AlertMessage/AlertMessage.style.tsx","../node_modules/@lifi/widget/components/AlertMessage/AlertMessage.tsx","../node_modules/@mui/material/Switch/switchClasses.js","../node_modules/@mui/material/internal/switchBaseClasses.js","../node_modules/@mui/material/internal/SwitchBase.js","../node_modules/@mui/material/Switch/Switch.js","../node_modules/@lifi/widget/components/Switch.tsx","../node_modules/@lifi/widget/components/GasMessage/GasMessage.style.ts","../node_modules/@lifi/widget/components/GasMessage/GasRefuelMessage.tsx","../node_modules/@mui/material/Link/linkClasses.js","../node_modules/@mui/material/Link/getTextDecoration.js","../node_modules/@mui/material/Link/Link.js","../node_modules/@lifi/widget/components/PoweredBy/PoweredBy.style.ts","../node_modules/@lifi/widget/components/PoweredBy/PoweredBy.tsx","../node_modules/@lifi/widget/node_modules/uuid/dist/esm-browser/native.js","../node_modules/@lifi/widget/node_modules/uuid/dist/esm-browser/rng.js","../node_modules/@lifi/widget/node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/@lifi/widget/node_modules/uuid/dist/esm-browser/v4.js","../node_modules/@lifi/widget/node_modules/viem/errors/version.ts","../node_modules/@lifi/widget/node_modules/viem/errors/base.ts","../node_modules/@lifi/widget/node_modules/viem/errors/unit.ts","../node_modules/@lifi/widget/node_modules/viem/utils/unit/parseUnits.ts","../node_modules/@lifi/widget/stores/routes/useSetExecutableRoute.ts","../node_modules/@lifi/widget/node_modules/viem/utils/lru.ts","../node_modules/@lifi/widget/node_modules/viem/utils/data/isHex.ts","../node_modules/@lifi/widget/node_modules/viem/errors/data.ts","../node_modules/@lifi/widget/node_modules/viem/utils/data/pad.ts","../node_modules/@lifi/widget/node_modules/viem/errors/encoding.ts","../node_modules/@lifi/widget/node_modules/viem/utils/data/size.ts","../node_modules/@lifi/widget/node_modules/viem/utils/encoding/fromHex.ts","../node_modules/@lifi/widget/node_modules/viem/utils/encoding/toHex.ts","../node_modules/@lifi/widget/node_modules/viem/utils/encoding/toBytes.ts","../node_modules/@lifi/widget/node_modules/viem/utils/address/getAddress.ts","../node_modules/@lifi/widget/node_modules/viem/utils/hash/keccak256.ts","../node_modules/@lifi/widget/node_modules/viem/utils/address/isAddress.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/_u64.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha512.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/abstract/edwards.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/ed25519.ts","../../src/error.ts","../../src/utils.ts","../../src/struct.ts","../../src/structs/utilities.ts","../../src/structs/types.ts","../../src/structs/coercions.ts","../node_modules/rpc-websockets/src/lib/client/websocket.browser.ts","../node_modules/rpc-websockets/src/lib/client.ts","../node_modules/rpc-websockets/src/lib/utils.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/@solana/web3.js/node_modules/@noble/curves/src/secp256k1.ts","../node_modules/@solana/web3.js/src/utils/ed25519.ts","../node_modules/@solana/web3.js/src/utils/to-buffer.ts","../node_modules/@solana/web3.js/src/utils/borsh-schema.ts","../node_modules/@solana/web3.js/src/publickey.ts","../node_modules/@solana/web3.js/src/bpf-loader-deprecated.ts","../node_modules/@solana/web3.js/src/transaction/constants.ts","../node_modules/@solana/web3.js/src/transaction/expiry-custom-errors.ts","../node_modules/@solana/web3.js/src/message/account-keys.ts","../node_modules/@solana/web3.js/src/layout.ts","../node_modules/@solana/web3.js/src/utils/shortvec-encoding.ts","../node_modules/@solana/web3.js/src/utils/assert.ts","../node_modules/@solana/web3.js/src/message/compiled-keys.ts","../node_modules/@solana/web3.js/src/utils/guarded-array-utils.ts","../node_modules/@solana/web3.js/src/message/legacy.ts","../node_modules/@solana/web3.js/src/message/v0.ts","../node_modules/@solana/web3.js/src/message/versioned.ts","../node_modules/@solana/web3.js/src/transaction/legacy.ts","../node_modules/@solana/web3.js/src/transaction/versioned.ts","../node_modules/@solana/web3.js/src/timing.ts","../node_modules/@solana/web3.js/src/sysvar.ts","../node_modules/@solana/web3.js/src/errors.ts","../node_modules/@solana/web3.js/src/utils/send-and-confirm-transaction.ts","../node_modules/@solana/web3.js/src/utils/sleep.ts","../node_modules/@solana/web3.js/src/instruction.ts","../node_modules/@solana/web3.js/src/fee-calculator.ts","../node_modules/@solana/web3.js/src/nonce-account.ts","../node_modules/@solana/web3.js/src/utils/bigint.ts","../node_modules/@solana/web3.js/src/programs/system.ts","../node_modules/@solana/web3.js/src/loader.ts","../node_modules/@solana/web3.js/src/bpf-loader.ts","../node_modules/@solana/web3.js/node_modules/.pnpm/fast-stable-stringify@1.0.0/node_modules/fast-stable-stringify/index.js","../node_modules/@solana/web3.js/src/epoch-schedule.ts","../node_modules/@solana/web3.js/src/__forks__/browser/fetch-impl.ts","../node_modules/@solana/web3.js/src/rpc-websocket.ts","../node_modules/@solana/web3.js/src/programs/address-lookup-table/state.ts","../node_modules/@solana/web3.js/src/account-data.ts","../node_modules/@solana/web3.js/src/utils/makeWebsocketUrl.ts","../node_modules/@solana/web3.js/src/connection.ts","../node_modules/@solana/web3.js/src/keypair.ts","../node_modules/@solana/web3.js/src/programs/address-lookup-table/index.ts","../node_modules/@solana/web3.js/src/programs/compute-budget.ts","../node_modules/@solana/web3.js/src/programs/ed25519.ts","../node_modules/@solana/web3.js/src/utils/secp256k1.ts","../node_modules/@solana/web3.js/src/programs/secp256k1.ts","../node_modules/@solana/web3.js/src/programs/stake.ts","../node_modules/@solana/web3.js/src/programs/vote.ts","../node_modules/@solana/web3.js/src/validator-info.ts","../node_modules/@solana/web3.js/src/vote-account.ts","../node_modules/@solana/web3.js/src/utils/cluster.ts","../node_modules/@solana/web3.js/src/index.ts","../node_modules/@lifi/widget/utils/chainType.ts","../node_modules/@lifi/widget/utils/svm.ts","../node_modules/@lifi/widget/hooks/useDebouncedWatch.ts","../node_modules/@lifi/widget/stores/settings/useSplitSubvariantStore.tsx","../node_modules/@lifi/widget/hooks/useSwapOnly.ts","../node_modules/@lifi/widget/hooks/useRoutes.ts","../node_modules/@mui/material/CircularProgress/circularProgressClasses.js","../node_modules/@mui/material/CircularProgress/CircularProgress.js","../node_modules/@mui/lab/LoadingButton/loadingButtonClasses.js","../node_modules/@mui/lab/LoadingButton/LoadingButton.js","../node_modules/@lifi/widget/components/ButtonTertiary.tsx","../node_modules/@lifi/widget/components/ProgressToNextUpdate.tsx","../node_modules/@mui/icons-material/esm/ExpandLess.js","../node_modules/@mui/icons-material/esm/ExpandMore.js","../node_modules/@lifi/widget/components/Card/CardIconButton.tsx","../node_modules/@lifi/widget/components/Card/CardLabel.tsx","../node_modules/@mui/material/Stepper/stepperClasses.js","../node_modules/@mui/material/Stepper/StepperContext.js","../node_modules/@mui/material/Step/StepContext.js","../node_modules/@mui/material/StepConnector/stepConnectorClasses.js","../node_modules/@mui/material/StepConnector/StepConnector.js","../node_modules/@mui/material/Stepper/Stepper.js","../node_modules/@mui/material/Step/stepClasses.js","../node_modules/@mui/material/Step/Step.js","../node_modules/@lifi/widget/icons/lifi.ts","../node_modules/@mui/material/internal/svg-icons/CheckCircle.js","../node_modules/@mui/material/internal/svg-icons/Warning.js","../node_modules/@mui/material/StepIcon/stepIconClasses.js","../node_modules/@mui/material/StepIcon/StepIcon.js","../node_modules/@mui/material/StepLabel/stepLabelClasses.js","../node_modules/@mui/material/StepLabel/StepLabel.js","../node_modules/@lifi/widget/components/StepActions/StepActions.style.tsx","../node_modules/@lifi/widget/utils/fees.ts","../node_modules/@lifi/widget/components/StepActions/StepFees.tsx","../node_modules/@lifi/widget/components/StepActions/StepActions.tsx","../node_modules/react-intersection-observer/src/observe.ts","../node_modules/react-intersection-observer/src/InView.tsx","../node_modules/@lifi/widget/components/TextFitter/TextFitter.tsx","../node_modules/react-intersection-observer/src/useInView.tsx","../node_modules/@lifi/widget/components/Token/Token.style.tsx","../node_modules/@lifi/widget/components/Token/Token.tsx","../node_modules/@lifi/widget/components/RouteCard/RouteCard.style.ts","../node_modules/@mui/icons-material/esm/LocalGasStationRounded.js","../node_modules/@lifi/widget/components/FeeBreakdownTooltip.tsx","../node_modules/@lifi/widget/node_modules/zustand/esm/index.mjs","../node_modules/@lifi/widget/components/TokenRate/TokenRate.style.ts","../node_modules/@lifi/widget/components/TokenRate/TokenRate.tsx","../node_modules/@lifi/widget/components/RouteCard/RouteCardEssentials.tsx","../node_modules/@mui/icons-material/esm/Layers.js","../node_modules/@lifi/widget/components/RouteCard/RouteCardEssentialsExpanded.tsx","../node_modules/@lifi/widget/components/RouteCard/RouteCard.tsx","../node_modules/@lifi/widget/components/RouteCard/RouteCardSkeleton.tsx","../node_modules/@mui/icons-material/esm/Route.js","../node_modules/@lifi/widget/components/RouteCard/RouteNotFoundCard.tsx","../node_modules/@lifi/widget/components/Routes/Routes.tsx","../node_modules/@mui/system/esm/useMediaQuery/useMediaQuery.js","../node_modules/@mui/icons-material/esm/ArrowDownward.js","../node_modules/@lifi/widget/stores/bookmarks/BookmarkStore.tsx","../node_modules/@lifi/widget/stores/bookmarks/createBookmarkStore.ts","../node_modules/@lifi/widget/stores/bookmarks/useBookmarkActions.ts","../node_modules/@lifi/widget/stores/bookmarks/useBookmarks.ts","../node_modules/@lifi/widget/hooks/useToAddressReset.ts","../node_modules/@lifi/widget/components/ReverseTokensButton/ReverseTokensButton.style.tsx","../node_modules/@lifi/widget/components/ReverseTokensButton/ReverseTokensButton.tsx","../node_modules/@mui/material/CardHeader/cardHeaderClasses.js","../node_modules/@mui/material/CardContent/cardContentClasses.js","../node_modules/@mui/material/CardContent/CardContent.js","../node_modules/@mui/material/CardHeader/CardHeader.js","../node_modules/@lifi/widget/components/Card/CardHeader.tsx","../node_modules/@lifi/widget/components/SelectTokenButton/SelectTokenButton.style.tsx","../node_modules/@lifi/widget/components/SelectTokenButton/SelectTokenButton.tsx","../node_modules/@lifi/widget/components/SelectChainAndToken.tsx","../node_modules/@mui/icons-material/esm/CloseRounded.js","../node_modules/@lifi/widget/hooks/useToAddressRequirements.ts","../node_modules/@lifi/widget/stores/settings/useSendToWalletStore.ts","../node_modules/@lifi/widget/utils/wallet.ts","../../../../src/utils/getConnectorIcon.ts","../../icons.ts","../node_modules/@mui/icons-material/esm/Wallet.js","../node_modules/@lifi/widget/components/Avatar/AccountAvatar.tsx","../node_modules/@lifi/widget/components/SendToWallet/SendToWallet.style.tsx","../node_modules/@lifi/widget/components/SendToWallet/SendToWalletButton.tsx","../node_modules/@lifi/widget/components/SendToWallet/SendToWalletExpandButton.tsx","../node_modules/@lifi/widget/hooks/useWideVariant.ts","../node_modules/@lifi/widget/hooks/useFromTokenSufficiency.ts","../node_modules/@lifi/widget/hooks/useGasSufficiency.ts","../node_modules/@mui/icons-material/esm/WarningRounded.js","../node_modules/@lifi/widget/components/GasMessage/FundsSufficiencyMessage.tsx","../node_modules/@lifi/widget/components/GasMessage/GasSufficiencyMessage.tsx","../node_modules/@lifi/widget/components/GasMessage/GasMessage.tsx","../node_modules/@lifi/widget/components/ToAddressRequiredMessage.tsx","../node_modules/@lifi/widget/pages/MainPage/MainMessages.tsx","../node_modules/@lifi/widget/components/BaseTransactionButton/BaseTransactionButton.tsx","../node_modules/@lifi/widget/pages/MainPage/ReviewButton.tsx","../node_modules/@lifi/widget/hooks/useNavigateBack.ts","../node_modules/@lifi/widget/pages/RoutesPage/RoutesPage.style.ts","../node_modules/@mui/material/utils/debounce.js","../node_modules/@lifi/widget/stores/chains/createChainOrderStore.ts","../node_modules/@lifi/widget/stores/chains/ChainOrderStore.tsx","../node_modules/@lifi/widget/stores/chains/useChainOrder.ts","../node_modules/@lifi/widget/components/ChainSelect/useChainSelect.ts","../node_modules/@lifi/widget/components/FullPageContainer.tsx","../node_modules/@mui/icons-material/esm/Search.js","../node_modules/@lifi/widget/components/Input.tsx","../node_modules/@lifi/widget/components/Search/SearchInput.style.tsx","../node_modules/@lifi/widget/components/Search/SearchInput.tsx","../node_modules/@mui/icons-material/esm/SearchOff.js","../node_modules/@lifi/widget/components/Search/SearchNotFound.style.tsx","../node_modules/@lifi/widget/components/Search/SearchNotFound.tsx","../node_modules/@lifi/widget/components/TokenList/useTokenSelect.ts","../node_modules/@lifi/widget/pages/SelectChainPage/SelectChainPage.tsx","../node_modules/@mui/icons-material/esm/CheckBoxOutlined.js","../node_modules/@mui/icons-material/esm/IndeterminateCheckBoxOutlined.js","../node_modules/@mui/icons-material/esm/CheckBoxOutlineBlankOutlined.js","../node_modules/@lifi/widget/hooks/useTools.ts","../node_modules/@lifi/widget/pages/SelectEnabledToolsPage.tsx","../node_modules/@lifi/widget/components/ChainSelect/ChainSelect.style.tsx","../node_modules/@lifi/widget/components/ChainSelect/ChainSelect.tsx","../node_modules/@lifi/widget/components/TokenList/TokenNotFound.tsx","../node_modules/@tanstack/virtual-core/src/utils.ts","../node_modules/@tanstack/virtual-core/src/index.ts","../node_modules/@tanstack/react-virtual/src/index.tsx","../node_modules/@mui/icons-material/esm/OpenInNewRounded.js","../node_modules/@mui/material/utils/ownerWindow.js","../node_modules/@mui/material/Slide/Slide.js","../node_modules/@lifi/widget/config/constants.ts","../node_modules/@lifi/widget/hooks/useExplorer.ts","../node_modules/@lifi/widget/components/ListItem/ListItemButton.tsx","../node_modules/@lifi/widget/components/ListItem/ListItem.tsx","../node_modules/@lifi/widget/components/TokenList/TokenList.style.tsx","../node_modules/@lifi/widget/components/TokenList/TokenListItem.tsx","../node_modules/@lifi/widget/components/TokenList/VirtualizedTokenList.tsx","../node_modules/@lifi/widget/components/TokenList/TokenList.tsx","../node_modules/@lifi/widget/components/TokenList/utils.ts","../node_modules/@lifi/widget/pages/SelectTokenPage/SearchTokenInput.tsx","../node_modules/@lifi/widget/pages/SelectTokenPage/useTokenListHeight.ts","../node_modules/@lifi/widget/pages/SelectTokenPage/SelectTokenPage.tsx","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/version.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/errors/base.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/utils/getVersion.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/errors/connector.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/utils/extractRpcUrls.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/errors/config.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/version.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/base.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/address.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/data/isHex.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/data.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/data/pad.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/encoding.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/data/size.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/encoding/fromHex.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/encoding/toHex.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/encoding/toBytes.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/hash/keccak256.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/lru.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/address/isAddress.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/address/getAddress.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/stringify.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/request.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/rpc.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/connectors/src/walletConnect.ts","../../../../src/connectors/utils.ts","../../../../src/connectors/walletConnect.ts","../../../../src/utils/isWalletInstalled.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/connectors/src/coinbaseWallet.ts","../../../../src/connectors/coinbase.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/promise/withRetry.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/wait.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/promise/withTimeout.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/connectors/src/metaMask.ts","../../../../src/connectors/metaMask.ts","../../../../src/utils/getWalletPriority.ts","../node_modules/@solana/wallet-adapter-base/src/adapter.ts","../node_modules/@solana/wallet-adapter-base/src/errors.ts","../node_modules/@wagmi/core/src/actions/getConnectors.ts","../node_modules/wagmi/src/hooks/useConnectors.ts","../node_modules/wagmi/src/hooks/useConnect.ts","../node_modules/@wagmi/core/src/query/connect.ts","../node_modules/@lifi/widget/config/coinbase.ts","../node_modules/@lifi/widget/config/metaMask.ts","../node_modules/@lifi/widget/config/walletConnect.ts","../node_modules/@lifi/widget/hooks/useWallets.ts","../node_modules/@lifi/widget/pages/SelectWalletPage/EVMListItemButton.tsx","../../../../src/utils/isWalletInstalledAsync.ts","../node_modules/@lifi/widget/pages/SelectWalletPage/SVMListItemButton.tsx","../node_modules/@lifi/widget/pages/SelectWalletPage/SelectWalletPage.tsx","../node_modules/@mui/icons-material/esm/MoreHoriz.js","../node_modules/@mui/icons-material/esm/TurnedIn.js","../node_modules/@mui/icons-material/esm/ContentCopyRounded.js","../node_modules/@mui/material/Divider/dividerClasses.js","../node_modules/@mui/material/ListItemIcon/listItemIconClasses.js","../node_modules/@mui/material/MenuItem/menuItemClasses.js","../node_modules/@mui/material/MenuItem/MenuItem.js","../node_modules/@mui/material/utils/ownerDocument.js","../node_modules/@mui/material/utils/getScrollbarSize.js","../node_modules/@mui/material/MenuList/MenuList.js","../node_modules/@mui/material/Popover/popoverClasses.js","../node_modules/@mui/material/Popover/Popover.js","../node_modules/@mui/material/Menu/menuClasses.js","../node_modules/@mui/material/Menu/Menu.js","../node_modules/@lifi/widget/components/Menu.tsx","../node_modules/@mui/icons-material/esm/Error.js","../node_modules/@mui/icons-material/esm/Info.js","../node_modules/@mui/material/Drawer/drawerClasses.js","../node_modules/@mui/material/Drawer/Drawer.js","../node_modules/@lifi/widget/components/BottomSheet/BottomSheet.tsx","../node_modules/@lifi/widget/hooks/useAddressValidation.ts","../node_modules/@lifi/sdk/src/services/getNameServiceAddress.ts","../node_modules/@mui/material/Alert/alertClasses.js","../node_modules/@mui/material/internal/svg-icons/SuccessOutlined.js","../node_modules/@mui/material/internal/svg-icons/ReportProblemOutlined.js","../node_modules/@mui/material/internal/svg-icons/ErrorOutline.js","../node_modules/@mui/material/internal/svg-icons/InfoOutlined.js","../node_modules/@mui/material/internal/svg-icons/Close.js","../node_modules/@mui/material/Alert/Alert.js","../node_modules/@lifi/widget/pages/SendToWallet/SendToWalletPage.style.tsx","../node_modules/@lifi/widget/pages/SendToWallet/BookmarkAddressSheet.tsx","../node_modules/@lifi/widget/pages/SendToWallet/EmptyListIndicator.tsx","../node_modules/@mui/icons-material/esm/TurnedInNot.js","../node_modules/@mui/icons-material/esm/History.js","../node_modules/@lifi/widget/components/Card/CardButton.style.tsx","../node_modules/@lifi/widget/components/Card/CardButton.tsx","../node_modules/@lifi/widget/pages/SendToWallet/ConfirmAddressSheet.tsx","../node_modules/@mui/icons-material/esm/AirlineStops.js","../node_modules/@lifi/widget/hooks/useSettingMonitor.ts","../node_modules/@lifi/widget/pages/SettingsPage/SettingsCard/SettingCard.style.tsx","../node_modules/@lifi/widget/pages/SettingsPage/SettingsCard/BadgedValue.tsx","../node_modules/@lifi/widget/pages/SettingsPage/BridgeAndExchangeSettings.tsx","../node_modules/@mui/utils/esm/scrollLeft/scrollLeft.js","../node_modules/@mui/material/internal/animate.js","../node_modules/@mui/material/Tabs/ScrollbarSize.js","../node_modules/@mui/material/internal/svg-icons/KeyboardArrowLeft.js","../node_modules/@mui/material/internal/svg-icons/KeyboardArrowRight.js","../node_modules/@mui/material/TabScrollButton/tabScrollButtonClasses.js","../node_modules/@mui/material/TabScrollButton/TabScrollButton.js","../node_modules/@mui/material/Tabs/tabsClasses.js","../node_modules/@mui/material/Tabs/Tabs.js","../node_modules/@mui/material/Tab/tabClasses.js","../node_modules/@mui/material/Tab/Tab.js","../node_modules/@lifi/widget/components/Tabs/Tabs.style.tsx","../node_modules/@lifi/widget/pages/SettingsPage/SettingsCard/SettingsAccordian.tsx","../node_modules/@lifi/widget/pages/SettingsPage/SettingsCard/SettingCardExpandable.tsx","../node_modules/@lifi/widget/pages/SettingsPage/GasPriceSettings.tsx","../node_modules/@mui/icons-material/esm/Language.js","../node_modules/@lifi/widget/pages/SettingsPage/LanguageSetting.tsx","../node_modules/@lifi/widget/pages/SettingsPage/ResetSettingsButton.style.tsx","../node_modules/@lifi/widget/pages/SettingsPage/ResetSettingsButton.tsx","../node_modules/@lifi/widget/pages/SettingsPage/RoutePrioritySettings.tsx","../node_modules/@mui/icons-material/esm/Percent.js","../node_modules/@lifi/widget/pages/SettingsPage/SlippageSettings/SlippageSettings.style.tsx","../node_modules/@lifi/widget/pages/SettingsPage/SlippageSettings/SlippageSettings.tsx","../node_modules/@mui/icons-material/esm/LightMode.js","../node_modules/@mui/icons-material/esm/Nightlight.js","../node_modules/@mui/icons-material/esm/BrightnessAuto.js","../node_modules/@lifi/widget/stores/settings/useAppearance.ts","../node_modules/@lifi/widget/pages/SettingsPage/ThemeSettings.tsx","../node_modules/@mui/material/Divider/Divider.js","../node_modules/@lifi/widget/components/StepDivider/StepDivider.style.tsx","../node_modules/@lifi/widget/components/StepDivider/StepDivider.tsx","../node_modules/@mui/icons-material/esm/LinkRounded.js","../node_modules/@lifi/widget/components/Step/CircularProgress.style.tsx","../node_modules/@lifi/widget/components/Step/DestinationWalletAddress.tsx","../node_modules/@mui/icons-material/esm/Done.js","../node_modules/@lifi/widget/components/Step/CircularProgress.tsx","../node_modules/@lifi/widget/components/Step/StepProcess.tsx","../node_modules/@lifi/widget/components/Step/Step.tsx","../node_modules/@lifi/widget/components/Step/StepList.tsx","../node_modules/@lifi/widget/components/TransactionDetails.tsx","../node_modules/@lifi/widget/utils/converters.ts","../node_modules/@lifi/widget/pages/TransactionDetailsPage/ContactSupportButton.tsx","../node_modules/@lifi/widget/pages/TransactionDetailsPage/TransactionDetailsSkeleton.tsx","../node_modules/@mui/icons-material/esm/OpenInNew.js","../node_modules/@lifi/widget/pages/TransactionDetailsPage/TransferIdCard.tsx","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/queriesObserver.ts","../node_modules/@lifi/widget/hooks/useTransactionHistory.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/src/useQueries.ts","../node_modules/@mui/icons-material/esm/ReceiptLongRounded.js","../node_modules/@lifi/widget/pages/TransactionHistoryPage/TransactionHistoryEmpty.tsx","../node_modules/@lifi/widget/pages/TransactionHistoryPage/TransactionHistoryItem.tsx","../node_modules/@lifi/widget/pages/TransactionHistoryPage/TransactionHistorySkeleton.tsx","../node_modules/@mui/icons-material/esm/Delete.js","../node_modules/@lifi/widget/hooks/useSetContentHeight.ts","../node_modules/@lifi/widget/pages/TransactionPage/StatusBottomSheet.style.tsx","../node_modules/@lifi/widget/pages/TransactionPage/ExchangeRateBottomSheet.tsx","../node_modules/@lifi/widget/pages/TransactionPage/RouteTracker.tsx","../node_modules/@lifi/widget/pages/TransactionPage/StartTransactionButton.tsx","../node_modules/@lifi/widget/pages/TransactionPage/StatusBottomSheet.tsx","../node_modules/@lifi/widget/pages/TransactionPage/utils.ts","../node_modules/@lifi/widget/pages/TransactionPage/TokenValueBottomSheet.tsx","../node_modules/@lifi/widget/AppRoutes.tsx","../node_modules/@lifi/widget/pages/MainPage/MainPage.tsx","../node_modules/@lifi/widget/pages/SettingsPage/SettingsPage.tsx","../node_modules/@lifi/widget/pages/LanguagesPage.tsx","../node_modules/@lifi/widget/pages/RoutesPage/RoutesPage.tsx","../node_modules/@lifi/widget/pages/SendToWallet/SendToWalletPage.tsx","../node_modules/@lifi/widget/pages/SendToWallet/BookmarksPage.tsx","../node_modules/@lifi/widget/pages/SendToWallet/RecentWalletsPage.tsx","../node_modules/@lifi/widget/pages/SendToWallet/ConnectedWalletsPage.tsx","../node_modules/@lifi/widget/pages/SendToWallet/SendToConfiguredWalletPage.tsx","../node_modules/@lifi/widget/pages/TransactionHistoryPage/TransactionHistoryPage.tsx","../node_modules/@lifi/widget/pages/TransactionHistoryPage/constants.ts","../node_modules/@lifi/widget/pages/TransactionDetailsPage/TransactionDetailsPage.tsx","../node_modules/@lifi/widget/hooks/useTransactionDetails.ts","../node_modules/@lifi/widget/pages/TransactionPage/TransactionPage.tsx","../node_modules/@mui/material/CssBaseline/CssBaseline.js","../node_modules/@mui/material/ScopedCssBaseline/scopedCssBaselineClasses.js","../node_modules/@mui/material/ScopedCssBaseline/ScopedCssBaseline.js","../node_modules/@lifi/widget/components/AppContainer.tsx","../node_modules/@mui/material/AppBar/appBarClasses.js","../node_modules/@mui/material/AppBar/AppBar.js","../node_modules/@lifi/widget/components/Header/Header.style.ts","../node_modules/@mui/icons-material/esm/ArrowBack.js","../node_modules/@lifi/widget/components/Header/BackButton.tsx","../node_modules/@lifi/widget/AppDrawerContext.ts","../node_modules/@lifi/widget/components/Header/CloseDrawerButton.tsx","../node_modules/@lifi/widget/components/Header/NavigationTabs.tsx","../node_modules/@mui/icons-material/esm/Settings.js","../node_modules/@lifi/widget/components/Header/SettingsButton.style.tsx","../node_modules/@lifi/widget/components/Header/SettingsButton.tsx","../node_modules/@mui/icons-material/esm/ReceiptLong.js","../node_modules/@lifi/widget/components/Header/TransactionHistoryButton.tsx","../node_modules/@mui/icons-material/esm/PowerSettingsNewRounded.js","../node_modules/@lifi/widget/components/Header/EVMDisconnectIconButton.tsx","../node_modules/@lifi/widget/components/Header/SVMDisconnectIconButton.tsx","../node_modules/@lifi/widget/components/Header/WalletMenu.tsx","../node_modules/@lifi/widget/components/Header/WalletMenu.style.tsx","../node_modules/@lifi/widget/components/Header/WalletHeader.tsx","../node_modules/@lifi/widget/components/Header/NavigationHeader.tsx","../node_modules/@lifi/widget/components/Header/Header.tsx","../node_modules/@lifi/widget/hooks/useInitializer.ts","../node_modules/@lifi/widget/components/Initializer.tsx","../node_modules/@lifi/widget/components/Routes/RoutesExpanded.style.ts","../node_modules/@lifi/widget/components/Routes/RoutesExpanded.tsx","../node_modules/@lifi/widget/AppDefault.tsx","../node_modules/@lifi/widget/AppDrawer.tsx","../node_modules/@lifi/widget/components/PageEntered.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/queryCache.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/mutationCache.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/infiniteQueryBehavior.ts","../node_modules/@lifi/widget/config/queryClient.ts","../node_modules/@lifi/widget/node_modules/@tanstack/react-query/node_modules/@tanstack/query-core/src/queryClient.ts","../node_modules/i18next/dist/esm/i18next.js","../node_modules/@lifi/widget/utils/deepMerge.ts","../node_modules/@lifi/widget/providers/I18nProvider/currencyExtendedFormatter.ts","../node_modules/@lifi/widget/providers/I18nProvider/percentFormatter.ts","../node_modules/@lifi/widget/providers/I18nProvider/I18nProvider.tsx","../node_modules/@mui/private-theming/useTheme/ThemeContext.js","../node_modules/@mui/private-theming/useTheme/useTheme.js","../node_modules/@mui/private-theming/ThemeProvider/nested.js","../node_modules/@mui/private-theming/ThemeProvider/ThemeProvider.js","../node_modules/@mui/system/esm/ThemeProvider/ThemeProvider.js","../node_modules/@mui/material/styles/ThemeProvider.js","../node_modules/@lifi/widget/themes/palettes.ts","../node_modules/@lifi/widget/themes/utils.ts","../node_modules/@lifi/widget/themes/createTheme.ts","../node_modules/@lifi/widget/providers/ThemeProvider/ThemeProvider.tsx","../node_modules/@lifi/wallet-management/node_modules/viem/utils/uid.ts","../node_modules/@lifi/wallet-management/node_modules/viem/clients/createClient.ts","../node_modules/@lifi/wallet-management/node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/@lifi/wallet-management/node_modules/viem/errors/transport.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/rpc/id.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/promise/withDedupe.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/buildRequest.ts","../node_modules/@lifi/wallet-management/node_modules/viem/clients/transports/http.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/rpc/http.ts","../node_modules/@lifi/wallet-management/node_modules/viem/clients/transports/createTransport.ts","../node_modules/@lifi/wallet-management/node_modules/viem/utils/chain/defineChain.ts","../node_modules/@lifi/wallet-management/node_modules/viem/chains/definitions/mainnet.ts","../node_modules/@lifi/wallet-management/node_modules/zustand/esm/middleware.mjs","../node_modules/@lifi/wallet-management/node_modules/zustand/esm/vanilla.mjs","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/connectors/injected.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/createEmitter.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/utils/deserialize.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/utils/serialize.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/createStorage.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/utils/uid.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/createConfig.ts","../../../../src/connectors/connectors.ts","../node_modules/@lifi/wallet-management/node_modules/@wagmi/core/src/actions/reconnect.ts","../../syncWagmiConfig.ts","../../../../src/utils/convertExtendedChain.ts","../node_modules/@lifi/widget/providers/WalletProvider/EVMBaseProvider.tsx","../../createDefaultWagmiConfig.ts","../../useSyncWagmiConfig.ts","../node_modules/@lifi/widget/providers/WalletProvider/EVMProvider.tsx","../node_modules/@lifi/sdk/node_modules/viem/errors/account.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/signature/recoverPublicKey.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/signature/recoverAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/encoding/toRlp.ts","../node_modules/@lifi/sdk/node_modules/viem/experimental/eip7702/utils/hashAuthorization.ts","../node_modules/@lifi/sdk/node_modules/viem/experimental/eip7702/utils/recoverAuthorizationAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/getAction.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getChainId.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/fee.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/block.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/formatters/transaction.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/formatters/block.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getBlock.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getGasPrice.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/estimateGas.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getBalance.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/estimateGas.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getTransactionCount.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/blob/blobsToCommitments.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/blob/blobsToProofs.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/hash/sha256.ts","../node_modules/@lifi/sdk/node_modules/viem/constants/blob.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/blob.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/blob/toBlobSidecars.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/blob/toBlobs.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/transaction/getTransactionType.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/wallet/sendTransaction.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/chain/assertCurrentChain.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/@lifi/sdk/src/utils/getTransactionMessage.ts","../node_modules/@lifi/sdk/src/core/processMessages.ts","../node_modules/@lifi/sdk/src/core/StatusManager.ts","../node_modules/@lifi/sdk/src/core/BaseStepExecutor.ts","../node_modules/@lifi/sdk/src/core/utils.ts","../node_modules/@lifi/sdk/src/core/checkBalance.ts","../node_modules/@lifi/sdk/src/core/stepComparison.ts","../node_modules/@lifi/sdk/src/core/waitForReceivingTransaction.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/rpc.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/errors/getContractError.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/readContract.ts","../node_modules/@lifi/sdk/src/core/EVM/abi.ts","../node_modules/@lifi/sdk/node_modules/viem/errors/transport.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/promise/withTimeout.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/rpc/id.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/rpc/http.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/rpc/socket.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/rpc/webSocket.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/promise/withDedupe.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/wait.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/promise/withRetry.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/buildRequest.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/uid.ts","../node_modules/@lifi/sdk/node_modules/viem/clients/transports/createTransport.ts","../node_modules/@lifi/sdk/node_modules/viem/clients/transports/webSocket.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/rpc/compat.ts","../node_modules/@lifi/sdk/node_modules/viem/clients/transports/fallback.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/chain/defineChain.ts","../node_modules/@lifi/sdk/node_modules/viem/chains/definitions/mainnet.ts","../node_modules/@lifi/sdk/src/core/rpc.ts","../node_modules/@lifi/sdk/src/core/EVM/publicClient.ts","../node_modules/@lifi/sdk/node_modules/viem/clients/transports/http.ts","../node_modules/@lifi/sdk/node_modules/viem/clients/createClient.ts","../node_modules/@lifi/sdk/src/core/EVM/getAllowance.ts","../node_modules/@lifi/sdk/src/core/EVM/parseEVMErrors.ts","../node_modules/@lifi/sdk/src/helpers.ts","../node_modules/@lifi/sdk/src/core/EVM/utils.ts","../node_modules/@lifi/sdk/src/utils/median.ts","../node_modules/@lifi/sdk/src/core/EVM/setAllowance.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/observe.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getTransaction.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/formatters/log.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/promise/withCache.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/poll.ts","../node_modules/@lifi/sdk/src/core/EVM/waitForTransactionReceipt.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/@lifi/sdk/src/core/EVM/checkAllowance.ts","../node_modules/@lifi/sdk/src/core/EVM/multisig.ts","../node_modules/@lifi/sdk/src/core/EVM/EVMStepExecutor.ts","../node_modules/@lifi/sdk/src/core/EVM/switchChain.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/wallet/getAddresses.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/namehash.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/labelhash.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/errors.ts","../node_modules/@lifi/sdk/node_modules/viem/utils/ens/normalize.ts","../node_modules/@lifi/sdk/src/core/EVM/getENSAddress.ts","../node_modules/@lifi/sdk/src/core/EVM/getEVMBalance.ts","../node_modules/@lifi/sdk/node_modules/viem/actions/public/multicall.ts","../node_modules/@lifi/sdk/src/core/Solana/connection.ts","../node_modules/@lifi/sdk/src/core/Solana/parseSolanaErrors.ts","../node_modules/@lifi/sdk/src/core/Solana/SolanaStepExecutor.ts","../node_modules/@lifi/sdk/src/utils/base64ToUint8Array.ts","../node_modules/@lifi/sdk/src/core/Solana/isAddress.ts","../node_modules/@lifi/sdk/src/core/Solana/getSNSAddress.ts","../node_modules/@lifi/sdk/src/core/Solana/types.ts","../node_modules/@lifi/sdk/src/core/Solana/getSolanaBalance.ts","../node_modules/viem/clients/decorators/wallet.ts","../node_modules/viem/actions/wallet/addChain.ts","../node_modules/viem/actions/wallet/deployContract.ts","../node_modules/viem/actions/wallet/getAddresses.ts","../node_modules/viem/actions/wallet/getPermissions.ts","../node_modules/viem/actions/wallet/requestAddresses.ts","../node_modules/viem/actions/wallet/requestPermissions.ts","../node_modules/viem/actions/wallet/signTransaction.ts","../node_modules/viem/actions/wallet/signTypedData.ts","../node_modules/viem/actions/wallet/switchChain.ts","../node_modules/viem/actions/wallet/watchAsset.ts","../node_modules/@wagmi/core/src/actions/getWalletClient.ts","../node_modules/@lifi/widget/providers/WalletProvider/SDKProviders.tsx","../node_modules/@lifi/sdk/src/core/EVM/EVM.ts","../node_modules/@lifi/sdk/src/core/Solana/Solana.ts","../node_modules/@solana/wallet-adapter-react/src/useConnection.ts","../node_modules/@solana/wallet-adapter-base/src/types.ts","../node_modules/@solana/wallet-adapter-react/src/ConnectionProvider.tsx","../node_modules/@solana/wallet-adapter-base/src/transaction.ts","../node_modules/@solana/wallet-adapter-base/src/signer.ts","../node_modules/@solana/wallet-standard-util/src/signIn.ts","../node_modules/@solana-mobile/mobile-wallet-adapter-protocol/lib/esm/index.js","../node_modules/@solana-mobile/mobile-wallet-adapter-protocol-web3js/lib/esm/index.js","../node_modules/@solana-mobile/wallet-adapter-mobile/lib/esm/index.js","../node_modules/@solana/wallet-standard-features/src/signAndSendTransaction.ts","../node_modules/@solana/wallet-standard-features/src/signTransaction.ts","../node_modules/@wallet-standard/features/src/connect.ts","../node_modules/@wallet-standard/features/src/events.ts","../node_modules/@solana/wallet-standard-wallet-adapter-base/src/types.ts","../node_modules/@solana/wallet-adapter-base/src/standard.ts","../node_modules/@solana/wallet-standard-features/src/signMessage.ts","../node_modules/@solana/wallet-standard-features/src/signIn.ts","../node_modules/@solana/wallet-standard-chains/src/index.ts","../node_modules/@solana/wallet-standard-util/src/endpoint.ts","../node_modules/@solana/wallet-standard-util/src/commitment.ts","../node_modules/@wallet-standard/features/src/disconnect.ts","../node_modules/@wallet-standard/wallet/src/util.ts","../node_modules/@solana/wallet-standard-wallet-adapter-base/src/adapter.ts","../node_modules/@wallet-standard/app/src/wallets.ts","../node_modules/@solana/wallet-standard-wallet-adapter-react/src/useStandardWalletAdapters.ts","../node_modules/@solana/wallet-adapter-react/src/getEnvironment.ts","../node_modules/@solana/wallet-adapter-react/src/getInferredClusterFromEndpoint.ts","../node_modules/@solana/wallet-adapter-react/src/errors.ts","../node_modules/@solana/wallet-adapter-react/src/WalletProviderBase.tsx","../node_modules/@solana/wallet-adapter-react/src/WalletProvider.tsx","../node_modules/@solana/wallet-adapter-react/src/useLocalStorage.ts","../node_modules/@lifi/widget/providers/WalletProvider/SVMBaseProvider.tsx","../node_modules/@lifi/widget/providers/WalletProvider/SVMProvider.tsx","../node_modules/@lifi/widget/providers/WalletProvider/WalletProvider.tsx","../node_modules/@lifi/widget/stores/form/createFormStore.ts","../node_modules/@lifi/widget/stores/form/FormUpdater.tsx","../node_modules/@lifi/widget/stores/form/FormStore.tsx","../node_modules/@lifi/widget/stores/form/useFormRef.ts","../node_modules/@lifi/widget/stores/StoreProvider.tsx","../node_modules/@lifi/widget/stores/form/URLSearchParamsBuilder.tsx","../node_modules/@lifi/widget/stores/form/useTouchedFields.ts","../node_modules/@lifi/widget/AppProvider.tsx","../node_modules/@lifi/widget/App.tsx","sections/Swapper.tsx","data/buyFaqs.ts","screens/BuyScreen.tsx","../node_modules/lucide-react/src/icons/arrow-right.ts","assets/mountain.svg","screens/NotFoundScreen.tsx","router.tsx","sections/Footer.tsx","App.tsx","../node_modules/styled-components/src/constructors/createGlobalStyle.ts","../../../../../../adapters/evm/wagmi/utils/defaultConfig.ts","../../../../../../adapters/evm/wagmi/connectors/AuthConnector.ts","reportWebVitals.ts","../node_modules/@sentry/react/src/sdk.ts","index.tsx"],"sourceRoot":"","sourcesContent":["var isDevelopment = false;\n\n/*\n\nBased off glamor's StyleSheet, thanks Sunil ❤️\n\nhigh performance StyleSheet for css-in-js systems\n\n- uses multiple style tags behind the scenes for millions of rules\n- uses `insertRule` for appending in production for *much* faster performance\n\n// usage\n\nimport { StyleSheet } from '@emotion/sheet'\n\nlet styleSheet = new StyleSheet({ key: '', container: document.head })\n\nstyleSheet.insert('#box { border: 1px solid red; }')\n- appends a css rule into the stylesheet\n\nstyleSheet.flush()\n- empties the stylesheet of all its contents\n\n*/\n\nfunction sheetForTag(tag) {\n if (tag.sheet) {\n return tag.sheet;\n } // this weirdness brought to you by firefox\n\n /* istanbul ignore next */\n\n\n for (var i = 0; i < document.styleSheets.length; i++) {\n if (document.styleSheets[i].ownerNode === tag) {\n return document.styleSheets[i];\n }\n } // this function should always return with a value\n // TS can't understand it though so we make it stop complaining here\n\n\n return undefined;\n}\n\nfunction createStyleElement(options) {\n var tag = document.createElement('style');\n tag.setAttribute('data-emotion', options.key);\n\n if (options.nonce !== undefined) {\n tag.setAttribute('nonce', options.nonce);\n }\n\n tag.appendChild(document.createTextNode(''));\n tag.setAttribute('data-s', '');\n return tag;\n}\n\nvar StyleSheet = /*#__PURE__*/function () {\n // Using Node instead of HTMLElement since container may be a ShadowRoot\n function StyleSheet(options) {\n var _this = this;\n\n this._insertTag = function (tag) {\n var before;\n\n if (_this.tags.length === 0) {\n if (_this.insertionPoint) {\n before = _this.insertionPoint.nextSibling;\n } else if (_this.prepend) {\n before = _this.container.firstChild;\n } else {\n before = _this.before;\n }\n } else {\n before = _this.tags[_this.tags.length - 1].nextSibling;\n }\n\n _this.container.insertBefore(tag, before);\n\n _this.tags.push(tag);\n };\n\n this.isSpeedy = options.speedy === undefined ? !isDevelopment : options.speedy;\n this.tags = [];\n this.ctr = 0;\n this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets\n\n this.key = options.key;\n this.container = options.container;\n this.prepend = options.prepend;\n this.insertionPoint = options.insertionPoint;\n this.before = null;\n }\n\n var _proto = StyleSheet.prototype;\n\n _proto.hydrate = function hydrate(nodes) {\n nodes.forEach(this._insertTag);\n };\n\n _proto.insert = function insert(rule) {\n // the max length is how many rules we have per style tag, it's 65000 in speedy mode\n // it's 1 in dev because we insert source maps that map a single rule to a location\n // and you can only have one source map per style tag\n if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {\n this._insertTag(createStyleElement(this));\n }\n\n var tag = this.tags[this.tags.length - 1];\n\n if (this.isSpeedy) {\n var sheet = sheetForTag(tag);\n\n try {\n // this is the ultrafast version, works across browsers\n // the big drawback is that the css won't be editable in devtools\n sheet.insertRule(rule, sheet.cssRules.length);\n } catch (e) {\n }\n } else {\n tag.appendChild(document.createTextNode(rule));\n }\n\n this.ctr++;\n };\n\n _proto.flush = function flush() {\n this.tags.forEach(function (tag) {\n var _tag$parentNode;\n\n return (_tag$parentNode = tag.parentNode) == null ? void 0 : _tag$parentNode.removeChild(tag);\n });\n this.tags = [];\n this.ctr = 0;\n };\n\n return StyleSheet;\n}();\n\nexport { StyleSheet };\n","/**\n * @param {number}\n * @return {number}\n */\nexport var abs = Math.abs\n\n/**\n * @param {number}\n * @return {string}\n */\nexport var from = String.fromCharCode\n\n/**\n * @param {object}\n * @return {object}\n */\nexport var assign = Object.assign\n\n/**\n * @param {string} value\n * @param {number} length\n * @return {number}\n */\nexport function hash (value, length) {\n\treturn charat(value, 0) ^ 45 ? (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3) : 0\n}\n\n/**\n * @param {string} value\n * @return {string}\n */\nexport function trim (value) {\n\treturn value.trim()\n}\n\n/**\n * @param {string} value\n * @param {RegExp} pattern\n * @return {string?}\n */\nexport function match (value, pattern) {\n\treturn (value = pattern.exec(value)) ? value[0] : value\n}\n\n/**\n * @param {string} value\n * @param {(string|RegExp)} pattern\n * @param {string} replacement\n * @return {string}\n */\nexport function replace (value, pattern, replacement) {\n\treturn value.replace(pattern, replacement)\n}\n\n/**\n * @param {string} value\n * @param {string} search\n * @return {number}\n */\nexport function indexof (value, search) {\n\treturn value.indexOf(search)\n}\n\n/**\n * @param {string} value\n * @param {number} index\n * @return {number}\n */\nexport function charat (value, index) {\n\treturn value.charCodeAt(index) | 0\n}\n\n/**\n * @param {string} value\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function substr (value, begin, end) {\n\treturn value.slice(begin, end)\n}\n\n/**\n * @param {string} value\n * @return {number}\n */\nexport function strlen (value) {\n\treturn value.length\n}\n\n/**\n * @param {any[]} value\n * @return {number}\n */\nexport function sizeof (value) {\n\treturn value.length\n}\n\n/**\n * @param {any} value\n * @param {any[]} array\n * @return {any}\n */\nexport function append (value, array) {\n\treturn array.push(value), value\n}\n\n/**\n * @param {string[]} array\n * @param {function} callback\n * @return {string}\n */\nexport function combine (array, callback) {\n\treturn array.map(callback).join('')\n}\n","import {from, trim, charat, strlen, substr, append, assign} from './Utility.js'\n\nexport var line = 1\nexport var column = 1\nexport var length = 0\nexport var position = 0\nexport var character = 0\nexport var characters = ''\n\n/**\n * @param {string} value\n * @param {object | null} root\n * @param {object | null} parent\n * @param {string} type\n * @param {string[] | string} props\n * @param {object[] | string} children\n * @param {number} length\n */\nexport function node (value, root, parent, type, props, children, length) {\n\treturn {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''}\n}\n\n/**\n * @param {object} root\n * @param {object} props\n * @return {object}\n */\nexport function copy (root, props) {\n\treturn assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)\n}\n\n/**\n * @return {number}\n */\nexport function char () {\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function prev () {\n\tcharacter = position > 0 ? charat(characters, --position) : 0\n\n\tif (column--, character === 10)\n\t\tcolumn = 1, line--\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function next () {\n\tcharacter = position < length ? charat(characters, position++) : 0\n\n\tif (column++, character === 10)\n\t\tcolumn = 1, line++\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function peek () {\n\treturn charat(characters, position)\n}\n\n/**\n * @return {number}\n */\nexport function caret () {\n\treturn position\n}\n\n/**\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function slice (begin, end) {\n\treturn substr(characters, begin, end)\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function token (type) {\n\tswitch (type) {\n\t\t// \\0 \\t \\n \\r \\s whitespace token\n\t\tcase 0: case 9: case 10: case 13: case 32:\n\t\t\treturn 5\n\t\t// ! + , / > @ ~ isolate token\n\t\tcase 33: case 43: case 44: case 47: case 62: case 64: case 126:\n\t\t// ; { } breakpoint token\n\t\tcase 59: case 123: case 125:\n\t\t\treturn 4\n\t\t// : accompanied token\n\t\tcase 58:\n\t\t\treturn 3\n\t\t// \" ' ( [ opening delimit token\n\t\tcase 34: case 39: case 40: case 91:\n\t\t\treturn 2\n\t\t// ) ] closing delimit token\n\t\tcase 41: case 93:\n\t\t\treturn 1\n\t}\n\n\treturn 0\n}\n\n/**\n * @param {string} value\n * @return {any[]}\n */\nexport function alloc (value) {\n\treturn line = column = 1, length = strlen(characters = value), position = 0, []\n}\n\n/**\n * @param {any} value\n * @return {any}\n */\nexport function dealloc (value) {\n\treturn characters = '', value\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function delimit (type) {\n\treturn trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))\n}\n\n/**\n * @param {string} value\n * @return {string[]}\n */\nexport function tokenize (value) {\n\treturn dealloc(tokenizer(alloc(value)))\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function whitespace (type) {\n\twhile (character = peek())\n\t\tif (character < 33)\n\t\t\tnext()\n\t\telse\n\t\t\tbreak\n\n\treturn token(type) > 2 || token(character) > 3 ? '' : ' '\n}\n\n/**\n * @param {string[]} children\n * @return {string[]}\n */\nexport function tokenizer (children) {\n\twhile (next())\n\t\tswitch (token(character)) {\n\t\t\tcase 0: append(identifier(position - 1), children)\n\t\t\t\tbreak\n\t\t\tcase 2: append(delimit(character), children)\n\t\t\t\tbreak\n\t\t\tdefault: append(from(character), children)\n\t\t}\n\n\treturn children\n}\n\n/**\n * @param {number} index\n * @param {number} count\n * @return {string}\n */\nexport function escaping (index, count) {\n\twhile (--count && next())\n\t\t// not 0-9 A-F a-f\n\t\tif (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))\n\t\t\tbreak\n\n\treturn slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function delimiter (type) {\n\twhile (next())\n\t\tswitch (character) {\n\t\t\t// ] ) \" '\n\t\t\tcase type:\n\t\t\t\treturn position\n\t\t\t// \" '\n\t\t\tcase 34: case 39:\n\t\t\t\tif (type !== 34 && type !== 39)\n\t\t\t\t\tdelimiter(character)\n\t\t\t\tbreak\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (type === 41)\n\t\t\t\t\tdelimiter(type)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tnext()\n\t\t\t\tbreak\n\t\t}\n\n\treturn position\n}\n\n/**\n * @param {number} type\n * @param {number} index\n * @return {number}\n */\nexport function commenter (type, index) {\n\twhile (next())\n\t\t// //\n\t\tif (type + character === 47 + 10)\n\t\t\tbreak\n\t\t// /*\n\t\telse if (type + character === 42 + 42 && peek() === 47)\n\t\t\tbreak\n\n\treturn '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next())\n}\n\n/**\n * @param {number} index\n * @return {string}\n */\nexport function identifier (index) {\n\twhile (!token(peek()))\n\t\tnext()\n\n\treturn slice(index, position)\n}\n","export var MS = '-ms-'\nexport var MOZ = '-moz-'\nexport var WEBKIT = '-webkit-'\n\nexport var COMMENT = 'comm'\nexport var RULESET = 'rule'\nexport var DECLARATION = 'decl'\n\nexport var PAGE = '@page'\nexport var MEDIA = '@media'\nexport var IMPORT = '@import'\nexport var CHARSET = '@charset'\nexport var VIEWPORT = '@viewport'\nexport var SUPPORTS = '@supports'\nexport var DOCUMENT = '@document'\nexport var NAMESPACE = '@namespace'\nexport var KEYFRAMES = '@keyframes'\nexport var FONT_FACE = '@font-face'\nexport var COUNTER_STYLE = '@counter-style'\nexport var FONT_FEATURE_VALUES = '@font-feature-values'\nexport var LAYER = '@layer'\n","import {IMPORT, LAYER, COMMENT, RULESET, DECLARATION, KEYFRAMES} from './Enum.js'\nimport {strlen, sizeof} from './Utility.js'\n\n/**\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function serialize (children, callback) {\n\tvar output = ''\n\tvar length = sizeof(children)\n\n\tfor (var i = 0; i < length; i++)\n\t\toutput += callback(children[i], i, children, callback) || ''\n\n\treturn output\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function stringify (element, index, children, callback) {\n\tswitch (element.type) {\n\t\tcase LAYER: if (element.children.length) break\n\t\tcase IMPORT: case DECLARATION: return element.return = element.return || element.value\n\t\tcase COMMENT: return ''\n\t\tcase KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}'\n\t\tcase RULESET: element.value = element.props.join(',')\n\t}\n\n\treturn strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''\n}\n","import {COMMENT, RULESET, DECLARATION} from './Enum.js'\nimport {abs, charat, trim, from, sizeof, strlen, substr, append, replace, indexof} from './Utility.js'\nimport {node, char, prev, next, peek, caret, alloc, dealloc, delimit, whitespace, escaping, identifier, commenter} from './Tokenizer.js'\n\n/**\n * @param {string} value\n * @return {object[]}\n */\nexport function compile (value) {\n\treturn dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value))\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {string[]} rule\n * @param {string[]} rules\n * @param {string[]} rulesets\n * @param {number[]} pseudo\n * @param {number[]} points\n * @param {string[]} declarations\n * @return {object}\n */\nexport function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {\n\tvar index = 0\n\tvar offset = 0\n\tvar length = pseudo\n\tvar atrule = 0\n\tvar property = 0\n\tvar previous = 0\n\tvar variable = 1\n\tvar scanning = 1\n\tvar ampersand = 1\n\tvar character = 0\n\tvar type = ''\n\tvar props = rules\n\tvar children = rulesets\n\tvar reference = rule\n\tvar characters = type\n\n\twhile (scanning)\n\t\tswitch (previous = character, character = next()) {\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (previous != 108 && charat(characters, length - 1) == 58) {\n\t\t\t\t\tif (indexof(characters += replace(delimit(character), '&', '&\\f'), '&\\f') != -1)\n\t\t\t\t\t\tampersand = -1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t// \" ' [\n\t\t\tcase 34: case 39: case 91:\n\t\t\t\tcharacters += delimit(character)\n\t\t\t\tbreak\n\t\t\t// \\t \\n \\r \\s\n\t\t\tcase 9: case 10: case 13: case 32:\n\t\t\t\tcharacters += whitespace(previous)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tcharacters += escaping(caret() - 1, 7)\n\t\t\t\tcontinue\n\t\t\t// /\n\t\t\tcase 47:\n\t\t\t\tswitch (peek()) {\n\t\t\t\t\tcase 42: case 47:\n\t\t\t\t\t\tappend(comment(commenter(next(), caret()), root, parent), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcharacters += '/'\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t// {\n\t\t\tcase 123 * variable:\n\t\t\t\tpoints[index++] = strlen(characters) * ampersand\n\t\t\t// } ; \\0\n\t\t\tcase 125 * variable: case 59: case 0:\n\t\t\t\tswitch (character) {\n\t\t\t\t\t// \\0 }\n\t\t\t\t\tcase 0: case 125: scanning = 0\n\t\t\t\t\t// ;\n\t\t\t\t\tcase 59 + offset: if (ampersand == -1) characters = replace(characters, /\\f/g, '')\n\t\t\t\t\t\tif (property > 0 && (strlen(characters) - length))\n\t\t\t\t\t\t\tappend(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @ ;\n\t\t\t\t\tcase 59: characters += ';'\n\t\t\t\t\t// { rule/at-rule\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tappend(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets)\n\n\t\t\t\t\t\tif (character === 123)\n\t\t\t\t\t\t\tif (offset === 0)\n\t\t\t\t\t\t\t\tparse(characters, root, reference, reference, props, rulesets, length, points, children)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tswitch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) {\n\t\t\t\t\t\t\t\t\t// d l m s\n\t\t\t\t\t\t\t\t\tcase 100: case 108: case 109: case 115:\n\t\t\t\t\t\t\t\t\t\tparse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\tparse(characters, reference, reference, reference, [''], children, 0, points, children)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tindex = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo\n\t\t\t\tbreak\n\t\t\t// :\n\t\t\tcase 58:\n\t\t\t\tlength = 1 + strlen(characters), property = previous\n\t\t\tdefault:\n\t\t\t\tif (variable < 1)\n\t\t\t\t\tif (character == 123)\n\t\t\t\t\t\t--variable\n\t\t\t\t\telse if (character == 125 && variable++ == 0 && prev() == 125)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\tswitch (characters += from(character), character * variable) {\n\t\t\t\t\t// &\n\t\t\t\t\tcase 38:\n\t\t\t\t\t\tampersand = offset > 0 ? 1 : (characters += '\\f', -1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// ,\n\t\t\t\t\tcase 44:\n\t\t\t\t\t\tpoints[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @\n\t\t\t\t\tcase 64:\n\t\t\t\t\t\t// -\n\t\t\t\t\t\tif (peek() === 45)\n\t\t\t\t\t\t\tcharacters += delimit(next())\n\n\t\t\t\t\t\tatrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// -\n\t\t\t\t\tcase 45:\n\t\t\t\t\t\tif (previous === 45 && strlen(characters) == 2)\n\t\t\t\t\t\t\tvariable = 0\n\t\t\t\t}\n\t\t}\n\n\treturn rulesets\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} index\n * @param {number} offset\n * @param {string[]} rules\n * @param {number[]} points\n * @param {string} type\n * @param {string[]} props\n * @param {string[]} children\n * @param {number} length\n * @return {object}\n */\nexport function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) {\n\tvar post = offset - 1\n\tvar rule = offset === 0 ? rules : ['']\n\tvar size = sizeof(rule)\n\n\tfor (var i = 0, j = 0, k = 0; i < index; ++i)\n\t\tfor (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)\n\t\t\tif (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\\f/g, rule[x])))\n\t\t\t\tprops[k++] = z\n\n\treturn node(value, root, parent, offset === 0 ? RULESET : type, props, children, length)\n}\n\n/**\n * @param {number} value\n * @param {object} root\n * @param {object?} parent\n * @return {object}\n */\nexport function comment (value, root, parent) {\n\treturn node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0)\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} length\n * @return {object}\n */\nexport function declaration (value, root, parent, length) {\n\treturn node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length)\n}\n","import { StyleSheet } from '@emotion/sheet';\nimport { dealloc, alloc, next, token, from, peek, delimit, slice, position, RULESET, combine, match, serialize, copy, replace, WEBKIT, MOZ, MS, KEYFRAMES, DECLARATION, hash, charat, strlen, indexof, stringify, rulesheet, middleware, compile } from 'stylis';\nimport '@emotion/weak-memoize';\nimport '@emotion/memoize';\n\nvar identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {\n var previous = 0;\n var character = 0;\n\n while (true) {\n previous = character;\n character = peek(); // &\\f\n\n if (previous === 38 && character === 12) {\n points[index] = 1;\n }\n\n if (token(character)) {\n break;\n }\n\n next();\n }\n\n return slice(begin, position);\n};\n\nvar toRules = function toRules(parsed, points) {\n // pretend we've started with a comma\n var index = -1;\n var character = 44;\n\n do {\n switch (token(character)) {\n case 0:\n // &\\f\n if (character === 38 && peek() === 12) {\n // this is not 100% correct, we don't account for literal sequences here - like for example quoted strings\n // stylis inserts \\f after & to know when & where it should replace this sequence with the context selector\n // and when it should just concatenate the outer and inner selectors\n // it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here\n points[index] = 1;\n }\n\n parsed[index] += identifierWithPointTracking(position - 1, points, index);\n break;\n\n case 2:\n parsed[index] += delimit(character);\n break;\n\n case 4:\n // comma\n if (character === 44) {\n // colon\n parsed[++index] = peek() === 58 ? '&\\f' : '';\n points[index] = parsed[index].length;\n break;\n }\n\n // fallthrough\n\n default:\n parsed[index] += from(character);\n }\n } while (character = next());\n\n return parsed;\n};\n\nvar getRules = function getRules(value, points) {\n return dealloc(toRules(alloc(value), points));\n}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11\n\n\nvar fixedElements = /* #__PURE__ */new WeakMap();\nvar compat = function compat(element) {\n if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo\n // negative .length indicates that this rule has been already prefixed\n element.length < 1) {\n return;\n }\n\n var value = element.value,\n parent = element.parent;\n var isImplicitRule = element.column === parent.column && element.line === parent.line;\n\n while (parent.type !== 'rule') {\n parent = parent.parent;\n if (!parent) return;\n } // short-circuit for the simplest case\n\n\n if (element.props.length === 1 && value.charCodeAt(0) !== 58\n /* colon */\n && !fixedElements.get(parent)) {\n return;\n } // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)\n // then the props has already been manipulated beforehand as they that array is shared between it and its \"rule parent\"\n\n\n if (isImplicitRule) {\n return;\n }\n\n fixedElements.set(element, true);\n var points = [];\n var rules = getRules(value, points);\n var parentRules = parent.props;\n\n for (var i = 0, k = 0; i < rules.length; i++) {\n for (var j = 0; j < parentRules.length; j++, k++) {\n element.props[k] = points[i] ? rules[i].replace(/&\\f/g, parentRules[j]) : parentRules[j] + \" \" + rules[i];\n }\n }\n};\nvar removeLabel = function removeLabel(element) {\n if (element.type === 'decl') {\n var value = element.value;\n\n if ( // charcode for l\n value.charCodeAt(0) === 108 && // charcode for b\n value.charCodeAt(2) === 98) {\n // this ignores label\n element[\"return\"] = '';\n element.value = '';\n }\n }\n};\n\n/* eslint-disable no-fallthrough */\n\nfunction prefix(value, length) {\n switch (hash(value, length)) {\n // color-adjust\n case 5103:\n return WEBKIT + 'print-' + value + value;\n // animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)\n\n case 5737:\n case 4201:\n case 3177:\n case 3433:\n case 1641:\n case 4457:\n case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break\n\n case 5572:\n case 6356:\n case 5844:\n case 3191:\n case 6645:\n case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,\n\n case 6391:\n case 5879:\n case 5623:\n case 6135:\n case 4599:\n case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)\n\n case 4215:\n case 6389:\n case 5109:\n case 5365:\n case 5621:\n case 3829:\n return WEBKIT + value + value;\n // appearance, user-select, transform, hyphens, text-size-adjust\n\n case 5349:\n case 4246:\n case 4810:\n case 6968:\n case 2756:\n return WEBKIT + value + MOZ + value + MS + value + value;\n // flex, flex-direction\n\n case 6828:\n case 4268:\n return WEBKIT + value + MS + value + value;\n // order\n\n case 6165:\n return WEBKIT + value + MS + 'flex-' + value + value;\n // align-items\n\n case 5187:\n return WEBKIT + value + replace(value, /(\\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;\n // align-self\n\n case 5443:\n return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;\n // align-content\n\n case 4675:\n return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;\n // flex-shrink\n\n case 5548:\n return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;\n // flex-basis\n\n case 5292:\n return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;\n // flex-grow\n\n case 6060:\n return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;\n // transition\n\n case 4554:\n return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;\n // cursor\n\n case 6187:\n return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;\n // background, background-image\n\n case 5495:\n case 3959:\n return replace(value, /(image-set\\([^]*)/, WEBKIT + '$1' + '$`$1');\n // justify-content\n\n case 4968:\n return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;\n // (margin|padding)-inline-(start|end)\n\n case 4095:\n case 3583:\n case 4068:\n case 2532:\n return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;\n // (min|max)?(width|height|inline-size|block-size)\n\n case 8116:\n case 7059:\n case 5753:\n case 5535:\n case 5445:\n case 5701:\n case 4933:\n case 4677:\n case 5533:\n case 5789:\n case 5021:\n case 4765:\n // stretch, max-content, min-content, fill-available\n if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {\n // (m)ax-content, (m)in-content\n case 109:\n // -\n if (charat(value, length + 4) !== 45) break;\n // (f)ill-available, (f)it-content\n\n case 102:\n return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;\n // (s)tretch\n\n case 115:\n return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;\n }\n break;\n // position: sticky\n\n case 4949:\n // (s)ticky?\n if (charat(value, length + 1) !== 115) break;\n // display: (flex|inline-flex)\n\n case 6444:\n switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {\n // stic(k)y\n case 107:\n return replace(value, ':', ':' + WEBKIT) + value;\n // (inline-)?fl(e)x\n\n case 101:\n return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;\n }\n\n break;\n // writing-mode\n\n case 5936:\n switch (charat(value, length + 11)) {\n // vertical-l(r)\n case 114:\n return WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'tb') + value;\n // vertical-r(l)\n\n case 108:\n return WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'tb-rl') + value;\n // horizontal(-)tb\n\n case 45:\n return WEBKIT + value + MS + replace(value, /[svh]\\w+-[tblr]{2}/, 'lr') + value;\n }\n\n return WEBKIT + value + MS + value + value;\n }\n\n return value;\n}\n\nvar prefixer = function prefixer(element, index, children, callback) {\n if (element.length > -1) if (!element[\"return\"]) switch (element.type) {\n case DECLARATION:\n element[\"return\"] = prefix(element.value, element.length);\n break;\n\n case KEYFRAMES:\n return serialize([copy(element, {\n value: replace(element.value, '@', '@' + WEBKIT)\n })], callback);\n\n case RULESET:\n if (element.length) return combine(element.props, function (value) {\n switch (match(value, /(::plac\\w+|:read-\\w+)/)) {\n // :read-(only|write)\n case ':read-only':\n case ':read-write':\n return serialize([copy(element, {\n props: [replace(value, /:(read-\\w+)/, ':' + MOZ + '$1')]\n })], callback);\n // :placeholder\n\n case '::placeholder':\n return serialize([copy(element, {\n props: [replace(value, /:(plac\\w+)/, ':' + WEBKIT + 'input-$1')]\n }), copy(element, {\n props: [replace(value, /:(plac\\w+)/, ':' + MOZ + '$1')]\n }), copy(element, {\n props: [replace(value, /:(plac\\w+)/, MS + 'input-$1')]\n })], callback);\n }\n\n return '';\n });\n }\n};\n\nvar defaultStylisPlugins = [prefixer];\n\nvar createCache = function\n /*: EmotionCache */\ncreateCache(options\n/*: Options */\n) {\n var key = options.key;\n\n if (key === 'css') {\n var ssrStyles = document.querySelectorAll(\"style[data-emotion]:not([data-s])\"); // get SSRed styles out of the way of React's hydration\n // document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)\n // note this very very intentionally targets all style elements regardless of the key to ensure\n // that creating a cache works inside of render of a React component\n\n Array.prototype.forEach.call(ssrStyles, function (node\n /*: HTMLStyleElement */\n ) {\n // we want to only move elements which have a space in the data-emotion attribute value\n // because that indicates that it is an Emotion 11 server-side rendered style elements\n // while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector\n // Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)\n // so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles\n // will not result in the Emotion 10 styles being destroyed\n var dataEmotionAttribute = node.getAttribute('data-emotion');\n\n if (dataEmotionAttribute.indexOf(' ') === -1) {\n return;\n }\n\n document.head.appendChild(node);\n node.setAttribute('data-s', '');\n });\n }\n\n var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;\n\n var inserted = {};\n var container;\n /* : Node */\n\n var nodesToHydrate = [];\n\n {\n container = options.container || document.head;\n Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which\n // means that the style elements we're looking at are only Emotion 11 server-rendered style elements\n document.querySelectorAll(\"style[data-emotion^=\\\"\" + key + \" \\\"]\"), function (node\n /*: HTMLStyleElement */\n ) {\n var attrib = node.getAttribute(\"data-emotion\").split(' ');\n\n for (var i = 1; i < attrib.length; i++) {\n inserted[attrib[i]] = true;\n }\n\n nodesToHydrate.push(node);\n });\n }\n\n var _insert;\n /*: (\n selector: string,\n serialized: SerializedStyles,\n sheet: StyleSheet,\n shouldCache: boolean\n ) => string | void */\n\n\n var omnipresentPlugins = [compat, removeLabel];\n\n {\n var currentSheet;\n var finalizingPlugins = [stringify, rulesheet(function (rule) {\n currentSheet.insert(rule);\n })];\n var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));\n\n var stylis = function stylis(styles) {\n return serialize(compile(styles), serializer);\n };\n\n _insert = function\n /*: void */\n insert(selector\n /*: string */\n , serialized\n /*: SerializedStyles */\n , sheet\n /*: StyleSheet */\n , shouldCache\n /*: boolean */\n ) {\n currentSheet = sheet;\n\n stylis(selector ? selector + \"{\" + serialized.styles + \"}\" : serialized.styles);\n\n if (shouldCache) {\n cache.inserted[serialized.name] = true;\n }\n };\n }\n\n var cache\n /*: EmotionCache */\n = {\n key: key,\n sheet: new StyleSheet({\n key: key,\n container: container,\n nonce: options.nonce,\n speedy: options.speedy,\n prepend: options.prepend,\n insertionPoint: options.insertionPoint\n }),\n nonce: options.nonce,\n inserted: inserted,\n registered: {},\n insert: _insert\n };\n cache.sheet.hydrate(nodesToHydrate);\n return cache;\n};\n\nexport { createCache as default };\n","import {MS, MOZ, WEBKIT, RULESET, KEYFRAMES, DECLARATION} from './Enum.js'\nimport {match, charat, substr, strlen, sizeof, replace, combine} from './Utility.js'\nimport {copy, tokenize} from './Tokenizer.js'\nimport {serialize} from './Serializer.js'\nimport {prefix} from './Prefixer.js'\n\n/**\n * @param {function[]} collection\n * @return {function}\n */\nexport function middleware (collection) {\n\tvar length = sizeof(collection)\n\n\treturn function (element, index, children, callback) {\n\t\tvar output = ''\n\n\t\tfor (var i = 0; i < length; i++)\n\t\t\toutput += collection[i](element, index, children, callback) || ''\n\n\t\treturn output\n\t}\n}\n\n/**\n * @param {function} callback\n * @return {function}\n */\nexport function rulesheet (callback) {\n\treturn function (element) {\n\t\tif (!element.root)\n\t\t\tif (element = element.return)\n\t\t\t\tcallback(element)\n\t}\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n */\nexport function prefixer (element, index, children, callback) {\n\tif (element.length > -1)\n\t\tif (!element.return)\n\t\t\tswitch (element.type) {\n\t\t\t\tcase DECLARATION: element.return = prefix(element.value, element.length, children)\n\t\t\t\t\treturn\n\t\t\t\tcase KEYFRAMES:\n\t\t\t\t\treturn serialize([copy(element, {value: replace(element.value, '@', '@' + WEBKIT)})], callback)\n\t\t\t\tcase RULESET:\n\t\t\t\t\tif (element.length)\n\t\t\t\t\t\treturn combine(element.props, function (value) {\n\t\t\t\t\t\t\tswitch (match(value, /(::plac\\w+|:read-\\w+)/)) {\n\t\t\t\t\t\t\t\t// :read-(only|write)\n\t\t\t\t\t\t\t\tcase ':read-only': case ':read-write':\n\t\t\t\t\t\t\t\t\treturn serialize([copy(element, {props: [replace(value, /:(read-\\w+)/, ':' + MOZ + '$1')]})], callback)\n\t\t\t\t\t\t\t\t// :placeholder\n\t\t\t\t\t\t\t\tcase '::placeholder':\n\t\t\t\t\t\t\t\t\treturn serialize([\n\t\t\t\t\t\t\t\t\t\tcopy(element, {props: [replace(value, /:(plac\\w+)/, ':' + WEBKIT + 'input-$1')]}),\n\t\t\t\t\t\t\t\t\t\tcopy(element, {props: [replace(value, /:(plac\\w+)/, ':' + MOZ + '$1')]}),\n\t\t\t\t\t\t\t\t\t\tcopy(element, {props: [replace(value, /:(plac\\w+)/, MS + 'input-$1')]})\n\t\t\t\t\t\t\t\t\t], callback)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn ''\n\t\t\t\t\t\t})\n\t\t\t}\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n */\nexport function namespace (element) {\n\tswitch (element.type) {\n\t\tcase RULESET:\n\t\t\telement.props = element.props.map(function (value) {\n\t\t\t\treturn combine(tokenize(value), function (value, index, children) {\n\t\t\t\t\tswitch (charat(value, 0)) {\n\t\t\t\t\t\t// \\f\n\t\t\t\t\t\tcase 12:\n\t\t\t\t\t\t\treturn substr(value, 1, strlen(value))\n\t\t\t\t\t\t// \\0 ( + > ~\n\t\t\t\t\t\tcase 0: case 40: case 43: case 62: case 126:\n\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t// :\n\t\t\t\t\t\tcase 58:\n\t\t\t\t\t\t\tif (children[++index] === 'global')\n\t\t\t\t\t\t\t\tchildren[index] = '', children[++index] = '\\f' + substr(children[index], index = 1, -1)\n\t\t\t\t\t\t// \\s\n\t\t\t\t\t\tcase 32:\n\t\t\t\t\t\t\treturn index === 1 ? '' : value\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tswitch (index) {\n\t\t\t\t\t\t\t\tcase 0: element = value\n\t\t\t\t\t\t\t\t\treturn sizeof(children) > 1 ? '' : value\n\t\t\t\t\t\t\t\tcase index = sizeof(children) - 1: case 2:\n\t\t\t\t\t\t\t\t\treturn index === 2 ? value + element + element : value + element\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t}\n}\n","function memoize(fn) {\n var cache = Object.create(null);\n return function (arg) {\n if (cache[arg] === undefined) cache[arg] = fn(arg);\n return cache[arg];\n };\n}\n\nexport { memoize as default };\n","import * as React from 'react';\nimport { useContext, forwardRef } from 'react';\nimport createCache from '@emotion/cache';\nimport _extends from '@babel/runtime/helpers/esm/extends';\nimport weakMemoize from '@emotion/weak-memoize';\nimport hoistNonReactStatics from '../_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js';\nimport { getRegisteredStyles, registerStyles, insertStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\nimport { useInsertionEffectAlwaysWithSyncFallback } from '@emotion/use-insertion-effect-with-fallbacks';\n\nvar isDevelopment = false;\n\n/* import { type EmotionCache } from '@emotion/utils' */\nvar EmotionCacheContext\n/*: React.Context */\n= /* #__PURE__ */React.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case\n// because this module is primarily intended for the browser and node\n// but it's also required in react native and similar environments sometimes\n// and we could have a special build just for that\n// but this is much easier and the native packages\n// might use a different theme context in the future anyway\ntypeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache({\n key: 'css'\n}) : null);\n\nvar CacheProvider = EmotionCacheContext.Provider;\nvar __unsafe_useEmotionCache = function useEmotionCache()\n/*: EmotionCache | null*/\n{\n return useContext(EmotionCacheContext);\n};\n\nvar withEmotionCache = function withEmotionCache\n/* > */\n(func\n/*: (props: Props, cache: EmotionCache, ref: Ref) => React.Node */\n)\n/*: React.AbstractComponent */\n{\n return /*#__PURE__*/forwardRef(function (props\n /*: Props */\n , ref\n /*: Ref */\n ) {\n // the cache will never be null in the browser\n var cache = useContext(EmotionCacheContext);\n return func(props, cache, ref);\n });\n};\n\nvar ThemeContext = /* #__PURE__ */React.createContext({});\n\nvar useTheme = function useTheme() {\n return React.useContext(ThemeContext);\n};\n\nvar getTheme = function getTheme(outerTheme\n/*: Object */\n, theme\n/*: Object | (Object => Object) */\n) {\n if (typeof theme === 'function') {\n var mergedTheme = theme(outerTheme);\n\n return mergedTheme;\n }\n\n return _extends({}, outerTheme, theme);\n};\n\nvar createCacheWithTheme = /* #__PURE__ */weakMemoize(function (outerTheme) {\n return weakMemoize(function (theme) {\n return getTheme(outerTheme, theme);\n });\n});\n/*\ntype ThemeProviderProps = {\n theme: Object | (Object => Object),\n children: React.Node\n}\n*/\n\nvar ThemeProvider = function ThemeProvider(props\n/*: ThemeProviderProps */\n) {\n var theme = React.useContext(ThemeContext);\n\n if (props.theme !== theme) {\n theme = createCacheWithTheme(theme)(props.theme);\n }\n\n return /*#__PURE__*/React.createElement(ThemeContext.Provider, {\n value: theme\n }, props.children);\n};\nfunction withTheme\n/* */\n(Component\n/*: React.AbstractComponent */\n)\n/*: React.AbstractComponent<$Diff> */\n{\n var componentName = Component.displayName || Component.name || 'Component';\n\n var render = function render(props, ref) {\n var theme = React.useContext(ThemeContext);\n return /*#__PURE__*/React.createElement(Component, _extends({\n theme: theme,\n ref: ref\n }, props));\n };\n\n var WithTheme = /*#__PURE__*/React.forwardRef(render);\n WithTheme.displayName = \"WithTheme(\" + componentName + \")\";\n return hoistNonReactStatics(WithTheme, Component);\n}\n\nvar hasOwn = {}.hasOwnProperty;\n\nvar typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';\nvar createEmotionProps = function createEmotionProps(type\n/*: React.ElementType */\n, props\n/*: Object */\n) {\n\n var newProps\n /*: any */\n = {};\n\n for (var key in props) {\n if (hasOwn.call(props, key)) {\n newProps[key] = props[key];\n }\n }\n\n newProps[typePropName] = type; // Runtime labeling is an opt-in feature because:\n\n return newProps;\n};\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serialized = _ref.serialized,\n isStringTag = _ref.isStringTag;\n registerStyles(cache, serialized, isStringTag);\n useInsertionEffectAlwaysWithSyncFallback(function () {\n return insertStyles(cache, serialized, isStringTag);\n });\n\n return null;\n};\n\nvar Emotion = /* #__PURE__ */withEmotionCache(\n/* */\nfunction (props, cache, ref) {\n var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works\n // not passing the registered cache to serializeStyles because it would\n // make certain babel optimisations not possible\n\n if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {\n cssProp = cache.registered[cssProp];\n }\n\n var WrappedComponent = props[typePropName];\n var registeredStyles = [cssProp];\n var className = '';\n\n if (typeof props.className === 'string') {\n className = getRegisteredStyles(cache.registered, registeredStyles, props.className);\n } else if (props.className != null) {\n className = props.className + \" \";\n }\n\n var serialized = serializeStyles(registeredStyles, undefined, React.useContext(ThemeContext));\n\n className += cache.key + \"-\" + serialized.name;\n var newProps = {};\n\n for (var key in props) {\n if (hasOwn.call(props, key) && key !== 'css' && key !== typePropName && (!isDevelopment )) {\n newProps[key] = props[key];\n }\n }\n\n newProps.className = className;\n\n if (ref) {\n newProps.ref = ref;\n }\n\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Insertion, {\n cache: cache,\n serialized: serialized,\n isStringTag: typeof WrappedComponent === 'string'\n }), /*#__PURE__*/React.createElement(WrappedComponent, newProps));\n});\n\nvar Emotion$1 = Emotion;\n\nexport { CacheProvider as C, Emotion$1 as E, ThemeContext as T, __unsafe_useEmotionCache as _, ThemeProvider as a, withTheme as b, createEmotionProps as c, hasOwn as h, isDevelopment as i, useTheme as u, withEmotionCache as w };\n","import { h as hasOwn, E as Emotion, c as createEmotionProps, w as withEmotionCache, T as ThemeContext, i as isDevelopment } from './emotion-element-5486c51c.browser.esm.js';\nexport { C as CacheProvider, T as ThemeContext, a as ThemeProvider, _ as __unsafe_useEmotionCache, u as useTheme, w as withEmotionCache, b as withTheme } from './emotion-element-5486c51c.browser.esm.js';\nimport * as React from 'react';\nimport { insertStyles, registerStyles, getRegisteredStyles } from '@emotion/utils';\nimport { useInsertionEffectWithLayoutFallback, useInsertionEffectAlwaysWithSyncFallback } from '@emotion/use-insertion-effect-with-fallbacks';\nimport { serializeStyles } from '@emotion/serialize';\nimport '@emotion/cache';\nimport '@babel/runtime/helpers/extends';\nimport '@emotion/weak-memoize';\nimport '../_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js';\nimport 'hoist-non-react-statics';\n\nvar jsx\n/*: typeof React.createElement */\n= function jsx\n/*: typeof React.createElement */\n(type\n/*: React.ElementType */\n, props\n/*: Object */\n) {\n var args = arguments;\n\n if (props == null || !hasOwn.call(props, 'css')) {\n return React.createElement.apply(undefined, args);\n }\n\n var argsLength = args.length;\n var createElementArgArray = new Array(argsLength);\n createElementArgArray[0] = Emotion;\n createElementArgArray[1] = createEmotionProps(type, props);\n\n for (var i = 2; i < argsLength; i++) {\n createElementArgArray[i] = args[i];\n }\n\n return React.createElement.apply(null, createElementArgArray);\n};\n\n// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild\n// initial client-side render from SSR, use place of hydrating tag\n\nvar Global\n/*: React.AbstractComponent<\nGlobalProps\n> */\n= /* #__PURE__ */withEmotionCache(function (props\n/*: GlobalProps */\n, cache) {\n\n var styles = props.styles;\n var serialized = serializeStyles([styles], undefined, React.useContext(ThemeContext));\n // but it is based on a constant that will never change at runtime\n // it's effectively like having two implementations and switching them out\n // so it's not actually breaking anything\n\n\n var sheetRef = React.useRef();\n useInsertionEffectWithLayoutFallback(function () {\n var key = cache.key + \"-global\"; // use case of https://github.com/emotion-js/emotion/issues/2675\n\n var sheet = new cache.sheet.constructor({\n key: key,\n nonce: cache.sheet.nonce,\n container: cache.sheet.container,\n speedy: cache.sheet.isSpeedy\n });\n var rehydrating = false;\n var node\n /*: HTMLStyleElement | null*/\n = document.querySelector(\"style[data-emotion=\\\"\" + key + \" \" + serialized.name + \"\\\"]\");\n\n if (cache.sheet.tags.length) {\n sheet.before = cache.sheet.tags[0];\n }\n\n if (node !== null) {\n rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other s\n\n node.setAttribute('data-emotion', key);\n sheet.hydrate([node]);\n }\n\n sheetRef.current = [sheet, rehydrating];\n return function () {\n sheet.flush();\n };\n }, [cache]);\n useInsertionEffectWithLayoutFallback(function () {\n var sheetRefCurrent = sheetRef.current;\n var sheet = sheetRefCurrent[0],\n rehydrating = sheetRefCurrent[1];\n\n if (rehydrating) {\n sheetRefCurrent[1] = false;\n return;\n }\n\n if (serialized.next !== undefined) {\n // insert keyframes\n insertStyles(cache, serialized.next, true);\n }\n\n if (sheet.tags.length) {\n // if this doesn't exist then it will be null so the style element will be appended\n var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;\n sheet.before = element;\n sheet.flush();\n }\n\n cache.insert(\"\", serialized, sheet, false);\n }, [cache, serialized.name]);\n return null;\n});\n\n/* import type { Interpolation, SerializedStyles } from '@emotion/utils' */\n\nfunction css()\n/*: SerializedStyles */\n{\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return serializeStyles(args);\n}\n\n/*\ntype Keyframes = {|\n name: string,\n styles: string,\n anim: 1,\n toString: () => string\n|} & string\n*/\n\nvar keyframes = function\n /*: Keyframes */\nkeyframes() {\n var insertable = css.apply(void 0, arguments);\n var name = \"animation-\" + insertable.name;\n return {\n name: name,\n styles: \"@keyframes \" + name + \"{\" + insertable.styles + \"}\",\n anim: 1,\n toString: function toString() {\n return \"_EMO_\" + this.name + \"_\" + this.styles + \"_EMO_\";\n }\n };\n};\n\n/*\ntype ClassNameArg =\n | string\n | boolean\n | { [key: string]: boolean }\n | Array\n | null\n | void\n*/\n\nvar classnames = function\n /*: string */\nclassnames(args\n/*: Array */\n) {\n var len = args.length;\n var i = 0;\n var cls = '';\n\n for (; i < len; i++) {\n var arg = args[i];\n if (arg == null) continue;\n var toAdd = void 0;\n\n switch (typeof arg) {\n case 'boolean':\n break;\n\n case 'object':\n {\n if (Array.isArray(arg)) {\n toAdd = classnames(arg);\n } else {\n\n toAdd = '';\n\n for (var k in arg) {\n if (arg[k] && k) {\n toAdd && (toAdd += ' ');\n toAdd += k;\n }\n }\n }\n\n break;\n }\n\n default:\n {\n toAdd = arg;\n }\n }\n\n if (toAdd) {\n cls && (cls += ' ');\n cls += toAdd;\n }\n }\n\n return cls;\n};\n\nfunction merge(registered\n/*: Object */\n, css\n/*: (...args: Array) => string */\n, className\n/*: string */\n) {\n var registeredStyles = [];\n var rawClassName = getRegisteredStyles(registered, registeredStyles, className);\n\n if (registeredStyles.length < 2) {\n return className;\n }\n\n return rawClassName + css(registeredStyles);\n}\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serializedArr = _ref.serializedArr;\n useInsertionEffectAlwaysWithSyncFallback(function () {\n\n for (var i = 0; i < serializedArr.length; i++) {\n insertStyles(cache, serializedArr[i], false);\n }\n });\n\n return null;\n};\n/*\ntype Props = {\n children: ({\n css: (...args: any) => string,\n cx: (...args: Array) => string,\n theme: Object\n }) => React.Node\n} */\n\n\nvar ClassNames\n/*: React.AbstractComponent*/\n= /* #__PURE__ */withEmotionCache(function (props, cache) {\n var hasRendered = false;\n var serializedArr = [];\n\n var css = function css() {\n if (hasRendered && isDevelopment) {\n throw new Error('css can only be used during render');\n }\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var serialized = serializeStyles(args, cache.registered);\n serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`\n\n registerStyles(cache, serialized, false);\n return cache.key + \"-\" + serialized.name;\n };\n\n var cx = function cx() {\n if (hasRendered && isDevelopment) {\n throw new Error('cx can only be used during render');\n }\n\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return merge(cache.registered, css, classnames(args));\n };\n\n var content = {\n css: css,\n cx: cx,\n theme: React.useContext(ThemeContext)\n };\n var ele = props.children(content);\n hasRendered = true;\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Insertion, {\n cache: cache,\n serializedArr: serializedArr\n }), ele);\n});\n\nexport { ClassNames, Global, jsx as createElement, css, jsx, keyframes };\n","var unitlessKeys = {\n animationIterationCount: 1,\n aspectRatio: 1,\n borderImageOutset: 1,\n borderImageSlice: 1,\n borderImageWidth: 1,\n boxFlex: 1,\n boxFlexGroup: 1,\n boxOrdinalGroup: 1,\n columnCount: 1,\n columns: 1,\n flex: 1,\n flexGrow: 1,\n flexPositive: 1,\n flexShrink: 1,\n flexNegative: 1,\n flexOrder: 1,\n gridRow: 1,\n gridRowEnd: 1,\n gridRowSpan: 1,\n gridRowStart: 1,\n gridColumn: 1,\n gridColumnEnd: 1,\n gridColumnSpan: 1,\n gridColumnStart: 1,\n msGridRow: 1,\n msGridRowSpan: 1,\n msGridColumn: 1,\n msGridColumnSpan: 1,\n fontWeight: 1,\n lineHeight: 1,\n opacity: 1,\n order: 1,\n orphans: 1,\n scale: 1,\n tabSize: 1,\n widows: 1,\n zIndex: 1,\n zoom: 1,\n WebkitLineClamp: 1,\n // SVG-related properties\n fillOpacity: 1,\n floodOpacity: 1,\n stopOpacity: 1,\n strokeDasharray: 1,\n strokeDashoffset: 1,\n strokeMiterlimit: 1,\n strokeOpacity: 1,\n strokeWidth: 1\n};\n\nexport { unitlessKeys as default };\n","import hashString from '@emotion/hash';\nimport unitless from '@emotion/unitless';\nimport memoize from '@emotion/memoize';\n\nvar isDevelopment = false;\n\nvar hyphenateRegex = /[A-Z]|^ms/g;\nvar animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;\n\nvar isCustomProperty = function isCustomProperty(property) {\n return property.charCodeAt(1) === 45;\n};\n\nvar isProcessableValue = function isProcessableValue(value) {\n return value != null && typeof value !== 'boolean';\n};\n\nvar processStyleName = /* #__PURE__ */memoize(function (styleName) {\n return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();\n});\n\nvar processStyleValue = function processStyleValue(key, value) {\n switch (key) {\n case 'animation':\n case 'animationName':\n {\n if (typeof value === 'string') {\n return value.replace(animationRegex, function (match, p1, p2) {\n cursor = {\n name: p1,\n styles: p2,\n next: cursor\n };\n return p1;\n });\n }\n }\n }\n\n if (unitless[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {\n return value + 'px';\n }\n\n return value;\n};\n\nvar noComponentSelectorMessage = 'Component selectors can only be used in conjunction with ' + '@emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware ' + 'compiler transform.';\n\nfunction handleInterpolation(mergedProps, registered, interpolation) {\n if (interpolation == null) {\n return '';\n }\n\n var componentSelector = interpolation;\n\n if (componentSelector.__emotion_styles !== undefined) {\n\n return componentSelector;\n }\n\n switch (typeof interpolation) {\n case 'boolean':\n {\n return '';\n }\n\n case 'object':\n {\n var keyframes = interpolation;\n\n if (keyframes.anim === 1) {\n cursor = {\n name: keyframes.name,\n styles: keyframes.styles,\n next: cursor\n };\n return keyframes.name;\n }\n\n var serializedStyles = interpolation;\n\n if (serializedStyles.styles !== undefined) {\n var next = serializedStyles.next;\n\n if (next !== undefined) {\n // not the most efficient thing ever but this is a pretty rare case\n // and there will be very few iterations of this generally\n while (next !== undefined) {\n cursor = {\n name: next.name,\n styles: next.styles,\n next: cursor\n };\n next = next.next;\n }\n }\n\n var styles = serializedStyles.styles + \";\";\n\n return styles;\n }\n\n return createStringFromObject(mergedProps, registered, interpolation);\n }\n\n case 'function':\n {\n if (mergedProps !== undefined) {\n var previousCursor = cursor;\n var result = interpolation(mergedProps);\n cursor = previousCursor;\n return handleInterpolation(mergedProps, registered, result);\n }\n\n break;\n }\n } // finalize string values (regular strings and functions interpolated into css calls)\n\n\n var asString = interpolation;\n\n if (registered == null) {\n return asString;\n }\n\n var cached = registered[asString];\n return cached !== undefined ? cached : asString;\n}\n\nfunction createStringFromObject(mergedProps, registered, obj) {\n var string = '';\n\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; i++) {\n string += handleInterpolation(mergedProps, registered, obj[i]) + \";\";\n }\n } else {\n for (var key in obj) {\n var value = obj[key];\n\n if (typeof value !== 'object') {\n var asString = value;\n\n if (registered != null && registered[asString] !== undefined) {\n string += key + \"{\" + registered[asString] + \"}\";\n } else if (isProcessableValue(asString)) {\n string += processStyleName(key) + \":\" + processStyleValue(key, asString) + \";\";\n }\n } else {\n if (key === 'NO_COMPONENT_SELECTOR' && isDevelopment) {\n throw new Error(noComponentSelectorMessage);\n }\n\n if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {\n for (var _i = 0; _i < value.length; _i++) {\n if (isProcessableValue(value[_i])) {\n string += processStyleName(key) + \":\" + processStyleValue(key, value[_i]) + \";\";\n }\n }\n } else {\n var interpolated = handleInterpolation(mergedProps, registered, value);\n\n switch (key) {\n case 'animation':\n case 'animationName':\n {\n string += processStyleName(key) + \":\" + interpolated + \";\";\n break;\n }\n\n default:\n {\n\n string += key + \"{\" + interpolated + \"}\";\n }\n }\n }\n }\n }\n }\n\n return string;\n}\n\nvar labelPattern = /label:\\s*([^\\s;{]+)\\s*(;|$)/g;\n// keyframes are stored on the SerializedStyles object as a linked list\n\n\nvar cursor;\nfunction serializeStyles(args, registered, mergedProps) {\n if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {\n return args[0];\n }\n\n var stringMode = true;\n var styles = '';\n cursor = undefined;\n var strings = args[0];\n\n if (strings == null || strings.raw === undefined) {\n stringMode = false;\n styles += handleInterpolation(mergedProps, registered, strings);\n } else {\n var asTemplateStringsArr = strings;\n\n styles += asTemplateStringsArr[0];\n } // we start at 1 since we've already handled the first arg\n\n\n for (var i = 1; i < args.length; i++) {\n styles += handleInterpolation(mergedProps, registered, args[i]);\n\n if (stringMode) {\n var templateStringsArr = strings;\n\n styles += templateStringsArr[i];\n }\n }\n\n\n labelPattern.lastIndex = 0;\n var identifierName = '';\n var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5\n\n while ((match = labelPattern.exec(styles)) !== null) {\n identifierName += '-' + match[1];\n }\n\n var name = hashString(styles) + identifierName;\n\n return {\n name: name,\n styles: styles,\n next: cursor\n };\n}\n\nexport { serializeStyles };\n","/* eslint-disable */\n// Inspired by https://github.com/garycourt/murmurhash-js\n// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86\nfunction murmur2(str) {\n // 'm' and 'r' are mixing constants generated offline.\n // They're not really 'magic', they just happen to work well.\n // const m = 0x5bd1e995;\n // const r = 24;\n // Initialize the hash\n var h = 0; // Mix 4 bytes at a time into the hash\n\n var k,\n i = 0,\n len = str.length;\n\n for (; len >= 4; ++i, len -= 4) {\n k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;\n k =\n /* Math.imul(k, m): */\n (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);\n k ^=\n /* k >>> r: */\n k >>> 24;\n h =\n /* Math.imul(k, m): */\n (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n } // Handle the last few bytes of the input array\n\n\n switch (len) {\n case 3:\n h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n\n case 2:\n h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n\n case 1:\n h ^= str.charCodeAt(i) & 0xff;\n h =\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n } // Do a few final mixes of the hash to ensure the last few\n // bytes are well-incorporated.\n\n\n h ^= h >>> 13;\n h =\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n return ((h ^ h >>> 15) >>> 0).toString(36);\n}\n\nexport { murmur2 as default };\n","import * as React from 'react';\n\nvar syncFallback = function syncFallback(create) {\n return create();\n};\n\nvar useInsertionEffect = React['useInsertion' + 'Effect'] ? React['useInsertion' + 'Effect'] : false;\nvar useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback;\nvar useInsertionEffectWithLayoutFallback = useInsertionEffect || React.useLayoutEffect;\n\nexport { useInsertionEffectAlwaysWithSyncFallback, useInsertionEffectWithLayoutFallback };\n","var isBrowser = true;\n\nfunction getRegisteredStyles(registered, registeredStyles, classNames) {\n var rawClassName = '';\n classNames.split(' ').forEach(function (className) {\n if (registered[className] !== undefined) {\n registeredStyles.push(registered[className] + \";\");\n } else if (className) {\n rawClassName += className + \" \";\n }\n });\n return rawClassName;\n}\nvar registerStyles = function registerStyles(cache, serialized, isStringTag) {\n var className = cache.key + \"-\" + serialized.name;\n\n if ( // we only need to add the styles to the registered cache if the\n // class name could be used further down\n // the tree but if it's a string tag, we know it won't\n // so we don't have to add it to registered cache.\n // this improves memory usage since we can avoid storing the whole style string\n (isStringTag === false || // we need to always store it if we're in compat mode and\n // in node since emotion-server relies on whether a style is in\n // the registered cache to know whether a style is global or not\n // also, note that this check will be dead code eliminated in the browser\n isBrowser === false ) && cache.registered[className] === undefined) {\n cache.registered[className] = serialized.styles;\n }\n};\nvar insertStyles = function insertStyles(cache, serialized, isStringTag) {\n registerStyles(cache, serialized, isStringTag);\n var className = cache.key + \"-\" + serialized.name;\n\n if (cache.inserted[serialized.name] === undefined) {\n var current = serialized;\n\n do {\n cache.insert(serialized === current ? \".\" + className : '', current, cache.sheet, true);\n\n current = current.next;\n } while (current !== undefined);\n }\n};\n\nexport { getRegisteredStyles, insertStyles, registerStyles };\n","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { Global } from '@emotion/react';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction isEmpty(obj) {\n return obj === undefined || obj === null || Object.keys(obj).length === 0;\n}\nexport default function GlobalStyles(props) {\n const {\n styles,\n defaultTheme = {}\n } = props;\n const globalStyles = typeof styles === 'function' ? themeInput => styles(isEmpty(themeInput) ? defaultTheme : themeInput) : styles;\n return /*#__PURE__*/_jsx(Global, {\n styles: globalStyles\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? GlobalStyles.propTypes = {\n defaultTheme: PropTypes.object,\n styles: PropTypes.oneOfType([PropTypes.array, PropTypes.string, PropTypes.object, PropTypes.func])\n} : void 0;","import memoize from '@emotion/memoize';\n\n// eslint-disable-next-line no-undef\nvar reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|fetchpriority|fetchPriority|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23\n\nvar isPropValid = /* #__PURE__ */memoize(function (prop) {\n return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111\n /* o */\n && prop.charCodeAt(1) === 110\n /* n */\n && prop.charCodeAt(2) < 91;\n}\n/* Z+1 */\n);\n\nexport { isPropValid as default };\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport * as React from 'react';\nimport isPropValid from '@emotion/is-prop-valid';\nimport { withEmotionCache, ThemeContext } from '@emotion/react';\nimport { getRegisteredStyles, registerStyles, insertStyles } from '@emotion/utils';\nimport { serializeStyles } from '@emotion/serialize';\nimport { useInsertionEffectAlwaysWithSyncFallback } from '@emotion/use-insertion-effect-with-fallbacks';\n\n/* import type {\n ElementType,\n StatelessFunctionalComponent,\n AbstractComponent\n} from 'react' */\n/*\nexport type Interpolations = Array\n\nexport type StyledElementType =\n | string\n | AbstractComponent<{ ...Props, className: string }, mixed>\n\nexport type StyledOptions = {\n label?: string,\n shouldForwardProp?: string => boolean,\n target?: string\n}\n\nexport type StyledComponent = StatelessFunctionalComponent & {\n defaultProps: any,\n toString: () => string,\n withComponent: (\n nextTag: StyledElementType,\n nextOptions?: StyledOptions\n ) => StyledComponent\n}\n\nexport type PrivateStyledComponent = StyledComponent & {\n __emotion_real: StyledComponent,\n __emotion_base: any,\n __emotion_styles: any,\n __emotion_forwardProp: any\n}\n*/\n\nvar testOmitPropsOnStringTag = isPropValid;\n\nvar testOmitPropsOnComponent = function testOmitPropsOnComponent(key\n/*: string */\n) {\n return key !== 'theme';\n};\n\nvar getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag\n/*: ElementType */\n) {\n return typeof tag === 'string' && // 96 is one less than the char code\n // for \"a\" so this is checking that\n // it's a lowercase character\n tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;\n};\nvar composeShouldForwardProps = function composeShouldForwardProps(tag\n/*: PrivateStyledComponent */\n, options\n/*: StyledOptions | void */\n, isReal\n/*: boolean */\n) {\n var shouldForwardProp;\n\n if (options) {\n var optionsShouldForwardProp = options.shouldForwardProp;\n shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName\n /*: string */\n ) {\n return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName);\n } : optionsShouldForwardProp;\n }\n\n if (typeof shouldForwardProp !== 'function' && isReal) {\n shouldForwardProp = tag.__emotion_forwardProp;\n }\n\n return shouldForwardProp;\n};\n/*\nexport type CreateStyledComponent = (\n ...args: Interpolations\n) => StyledComponent\n\nexport type CreateStyled = {\n (\n tag: StyledElementType,\n options?: StyledOptions\n ): (...args: Interpolations) => StyledComponent,\n [key: string]: CreateStyledComponent,\n bind: () => CreateStyled\n}\n*/\n\nvar isDevelopment = false;\n\nvar Insertion = function Insertion(_ref) {\n var cache = _ref.cache,\n serialized = _ref.serialized,\n isStringTag = _ref.isStringTag;\n registerStyles(cache, serialized, isStringTag);\n useInsertionEffectAlwaysWithSyncFallback(function () {\n return insertStyles(cache, serialized, isStringTag);\n });\n\n return null;\n};\n\nvar createStyled\n/*: CreateStyled */\n= function createStyled\n/*: CreateStyled */\n(tag\n/*: any */\n, options\n/* ?: StyledOptions */\n) {\n\n var isReal = tag.__emotion_real === tag;\n var baseTag = isReal && tag.__emotion_base || tag;\n var identifierName;\n var targetClassName;\n\n if (options !== undefined) {\n identifierName = options.label;\n targetClassName = options.target;\n }\n\n var shouldForwardProp = composeShouldForwardProps(tag, options, isReal);\n var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);\n var shouldUseAs = !defaultShouldForwardProp('as');\n /* return function(): PrivateStyledComponent { */\n\n return function () {\n var args = arguments;\n var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];\n\n if (identifierName !== undefined) {\n styles.push(\"label:\" + identifierName + \";\");\n }\n\n if (args[0] == null || args[0].raw === undefined) {\n styles.push.apply(styles, args);\n } else {\n\n styles.push(args[0][0]);\n var len = args.length;\n var i = 1;\n\n for (; i < len; i++) {\n\n styles.push(args[i], args[0][i]);\n }\n }\n\n var Styled\n /*: PrivateStyledComponent */\n = withEmotionCache(function (props, cache, ref) {\n var FinalTag = shouldUseAs && props.as || baseTag;\n var className = '';\n var classInterpolations = [];\n var mergedProps = props;\n\n if (props.theme == null) {\n mergedProps = {};\n\n for (var key in props) {\n mergedProps[key] = props[key];\n }\n\n mergedProps.theme = React.useContext(ThemeContext);\n }\n\n if (typeof props.className === 'string') {\n className = getRegisteredStyles(cache.registered, classInterpolations, props.className);\n } else if (props.className != null) {\n className = props.className + \" \";\n }\n\n var serialized = serializeStyles(styles.concat(classInterpolations), cache.registered, mergedProps);\n className += cache.key + \"-\" + serialized.name;\n\n if (targetClassName !== undefined) {\n className += \" \" + targetClassName;\n }\n\n var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;\n var newProps = {};\n\n for (var _key in props) {\n if (shouldUseAs && _key === 'as') continue;\n\n if (finalShouldForwardProp(_key)) {\n newProps[_key] = props[_key];\n }\n }\n\n newProps.className = className;\n\n if (ref) {\n newProps.ref = ref;\n }\n\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Insertion, {\n cache: cache,\n serialized: serialized,\n isStringTag: typeof FinalTag === 'string'\n }), /*#__PURE__*/React.createElement(FinalTag, newProps));\n });\n Styled.displayName = identifierName !== undefined ? identifierName : \"Styled(\" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + \")\";\n Styled.defaultProps = tag.defaultProps;\n Styled.__emotion_real = Styled;\n Styled.__emotion_base = baseTag;\n Styled.__emotion_styles = styles;\n Styled.__emotion_forwardProp = shouldForwardProp;\n Object.defineProperty(Styled, 'toString', {\n value: function value() {\n if (targetClassName === undefined && isDevelopment) {\n return 'NO_COMPONENT_SELECTOR';\n }\n\n return \".\" + targetClassName;\n }\n });\n\n Styled.withComponent = function (nextTag\n /*: StyledElementType */\n , nextOptions\n /* ?: StyledOptions */\n ) {\n return createStyled(nextTag, _extends({}, options, nextOptions, {\n shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true)\n })).apply(void 0, styles);\n };\n\n return Styled;\n };\n};\n\nexport { createStyled as default };\n","import createStyled from '../base/dist/emotion-styled-base.browser.esm.js';\nimport '@babel/runtime/helpers/extends';\nimport 'react';\nimport '@emotion/is-prop-valid';\nimport '@emotion/react';\nimport '@emotion/utils';\nimport '@emotion/serialize';\nimport '@emotion/use-insertion-effect-with-fallbacks';\n\nvar tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG\n'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];\n\nvar newStyled = createStyled.bind();\ntags.forEach(function (tagName) {\n newStyled[tagName] = newStyled(tagName);\n});\n\nexport { newStyled as default };\n","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { CacheProvider } from '@emotion/react';\nimport createCache from '@emotion/cache';\n\n// prepend: true moves MUI styles to the top of the so they're loaded first.\n// It allows developers to easily override MUI styles with other styling solutions, like CSS modules.\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nlet cache;\nif (typeof document === 'object') {\n cache = createCache({\n key: 'css',\n prepend: true\n });\n}\nexport default function StyledEngineProvider(props) {\n const {\n injectFirst,\n children\n } = props;\n return injectFirst && cache ? /*#__PURE__*/_jsx(CacheProvider, {\n value: cache,\n children: children\n }) : children;\n}\nprocess.env.NODE_ENV !== \"production\" ? StyledEngineProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: PropTypes.node,\n /**\n * By default, the styles are injected last in the element of the page.\n * As a result, they gain more specificity than any other style sheet.\n * If you want to override MUI's styles, set this prop.\n */\n injectFirst: PropTypes.bool\n} : void 0;","/**\n * @mui/styled-engine v5.16.6\n *\n * @license MIT\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use client';\n\n/* eslint-disable no-underscore-dangle */\nimport emStyled from '@emotion/styled';\nexport default function styled(tag, options) {\n const stylesFactory = emStyled(tag, options);\n if (process.env.NODE_ENV !== 'production') {\n return (...styles) => {\n const component = typeof tag === 'string' ? `\"${tag}\"` : 'component';\n if (styles.length === 0) {\n console.error([`MUI: Seems like you called \\`styled(${component})()\\` without a \\`style\\` argument.`, 'You must provide a `styles` argument: `styled(\"div\")(styleYouForgotToPass)`.'].join('\\n'));\n } else if (styles.some(style => style === undefined)) {\n console.error(`MUI: the styled(${component})(...args) API requires all its args to be defined.`);\n }\n return stylesFactory(...styles);\n };\n }\n return stylesFactory;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const internal_processStyles = (tag, processor) => {\n // Emotion attaches all the styles as `__emotion_styles`.\n // Ref: https://github.com/emotion-js/emotion/blob/16d971d0da229596d6bcc39d282ba9753c9ee7cf/packages/styled/src/base.js#L186\n if (Array.isArray(tag.__emotion_styles)) {\n tag.__emotion_styles = processor(tag.__emotion_styles);\n }\n};\nexport { ThemeContext, keyframes, css } from '@emotion/react';\nexport { default as StyledEngineProvider } from './StyledEngineProvider';\nexport { default as GlobalStyles } from './GlobalStyles';","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.alpha = alpha;\nexports.blend = blend;\nexports.colorChannel = void 0;\nexports.darken = darken;\nexports.decomposeColor = decomposeColor;\nexports.emphasize = emphasize;\nexports.getContrastRatio = getContrastRatio;\nexports.getLuminance = getLuminance;\nexports.hexToRgb = hexToRgb;\nexports.hslToRgb = hslToRgb;\nexports.lighten = lighten;\nexports.private_safeAlpha = private_safeAlpha;\nexports.private_safeColorChannel = void 0;\nexports.private_safeDarken = private_safeDarken;\nexports.private_safeEmphasize = private_safeEmphasize;\nexports.private_safeLighten = private_safeLighten;\nexports.recomposeColor = recomposeColor;\nexports.rgbToHex = rgbToHex;\nvar _formatMuiErrorMessage2 = _interopRequireDefault(require(\"@mui/utils/formatMuiErrorMessage\"));\nvar _clamp = _interopRequireDefault(require(\"@mui/utils/clamp\"));\n/* eslint-disable @typescript-eslint/naming-convention */\n\n/**\n * Returns a number whose value is limited to the given range.\n * @param {number} value The value to be clamped\n * @param {number} min The lower boundary of the output range\n * @param {number} max The upper boundary of the output range\n * @returns {number} A number in the range [min, max]\n */\nfunction clampWrapper(value, min = 0, max = 1) {\n if (process.env.NODE_ENV !== 'production') {\n if (value < min || value > max) {\n console.error(`MUI: The value provided ${value} is out of range [${min}, ${max}].`);\n }\n }\n return (0, _clamp.default)(value, min, max);\n}\n\n/**\n * Converts a color from CSS hex format to CSS rgb format.\n * @param {string} color - Hex color, i.e. #nnn or #nnnnnn\n * @returns {string} A CSS rgb color string\n */\nfunction hexToRgb(color) {\n color = color.slice(1);\n const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');\n let colors = color.match(re);\n if (colors && colors[0].length === 1) {\n colors = colors.map(n => n + n);\n }\n return colors ? `rgb${colors.length === 4 ? 'a' : ''}(${colors.map((n, index) => {\n return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;\n }).join(', ')})` : '';\n}\nfunction intToHex(int) {\n const hex = int.toString(16);\n return hex.length === 1 ? `0${hex}` : hex;\n}\n\n/**\n * Returns an object with the type and values of a color.\n *\n * Note: Does not support rgb % values.\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @returns {object} - A MUI color object: {type: string, values: number[]}\n */\nfunction decomposeColor(color) {\n // Idempotent\n if (color.type) {\n return color;\n }\n if (color.charAt(0) === '#') {\n return decomposeColor(hexToRgb(color));\n }\n const marker = color.indexOf('(');\n const type = color.substring(0, marker);\n if (['rgb', 'rgba', 'hsl', 'hsla', 'color'].indexOf(type) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? `MUI: Unsupported \\`${color}\\` color.\nThe following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().` : (0, _formatMuiErrorMessage2.default)(9, color));\n }\n let values = color.substring(marker + 1, color.length - 1);\n let colorSpace;\n if (type === 'color') {\n values = values.split(' ');\n colorSpace = values.shift();\n if (values.length === 4 && values[3].charAt(0) === '/') {\n values[3] = values[3].slice(1);\n }\n if (['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].indexOf(colorSpace) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? `MUI: unsupported \\`${colorSpace}\\` color space.\nThe following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.` : (0, _formatMuiErrorMessage2.default)(10, colorSpace));\n }\n } else {\n values = values.split(',');\n }\n values = values.map(value => parseFloat(value));\n return {\n type,\n values,\n colorSpace\n };\n}\n\n/**\n * Returns a channel created from the input color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @returns {string} - The channel for the color, that can be used in rgba or hsla colors\n */\nconst colorChannel = color => {\n const decomposedColor = decomposeColor(color);\n return decomposedColor.values.slice(0, 3).map((val, idx) => decomposedColor.type.indexOf('hsl') !== -1 && idx !== 0 ? `${val}%` : val).join(' ');\n};\nexports.colorChannel = colorChannel;\nconst private_safeColorChannel = (color, warning) => {\n try {\n return colorChannel(color);\n } catch (error) {\n if (warning && process.env.NODE_ENV !== 'production') {\n console.warn(warning);\n }\n return color;\n }\n};\n\n/**\n * Converts a color object with type and values to a string.\n * @param {object} color - Decomposed color\n * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla', 'color'\n * @param {array} color.values - [n,n,n] or [n,n,n,n]\n * @returns {string} A CSS color string\n */\nexports.private_safeColorChannel = private_safeColorChannel;\nfunction recomposeColor(color) {\n const {\n type,\n colorSpace\n } = color;\n let {\n values\n } = color;\n if (type.indexOf('rgb') !== -1) {\n // Only convert the first 3 values to int (i.e. not alpha)\n values = values.map((n, i) => i < 3 ? parseInt(n, 10) : n);\n } else if (type.indexOf('hsl') !== -1) {\n values[1] = `${values[1]}%`;\n values[2] = `${values[2]}%`;\n }\n if (type.indexOf('color') !== -1) {\n values = `${colorSpace} ${values.join(' ')}`;\n } else {\n values = `${values.join(', ')}`;\n }\n return `${type}(${values})`;\n}\n\n/**\n * Converts a color from CSS rgb format to CSS hex format.\n * @param {string} color - RGB color, i.e. rgb(n, n, n)\n * @returns {string} A CSS rgb color string, i.e. #nnnnnn\n */\nfunction rgbToHex(color) {\n // Idempotent\n if (color.indexOf('#') === 0) {\n return color;\n }\n const {\n values\n } = decomposeColor(color);\n return `#${values.map((n, i) => intToHex(i === 3 ? Math.round(255 * n) : n)).join('')}`;\n}\n\n/**\n * Converts a color from hsl format to rgb format.\n * @param {string} color - HSL color values\n * @returns {string} rgb color values\n */\nfunction hslToRgb(color) {\n color = decomposeColor(color);\n const {\n values\n } = color;\n const h = values[0];\n const s = values[1] / 100;\n const l = values[2] / 100;\n const a = s * Math.min(l, 1 - l);\n const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n let type = 'rgb';\n const rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];\n if (color.type === 'hsla') {\n type += 'a';\n rgb.push(values[3]);\n }\n return recomposeColor({\n type,\n values: rgb\n });\n}\n/**\n * The relative brightness of any point in a color space,\n * normalized to 0 for darkest black and 1 for lightest white.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @returns {number} The relative brightness of the color in the range 0 - 1\n */\nfunction getLuminance(color) {\n color = decomposeColor(color);\n let rgb = color.type === 'hsl' || color.type === 'hsla' ? decomposeColor(hslToRgb(color)).values : color.values;\n rgb = rgb.map(val => {\n if (color.type !== 'color') {\n val /= 255; // normalized\n }\n return val <= 0.03928 ? val / 12.92 : ((val + 0.055) / 1.055) ** 2.4;\n });\n\n // Truncate at 3 digits\n return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));\n}\n\n/**\n * Calculates the contrast ratio between two colors.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} A contrast ratio value in the range 0 - 21.\n */\nfunction getContrastRatio(foreground, background) {\n const lumA = getLuminance(foreground);\n const lumB = getLuminance(background);\n return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n}\n\n/**\n * Sets the absolute transparency of a color.\n * Any existing alpha values are overwritten.\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @param {number} value - value to set the alpha channel to in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\nfunction alpha(color, value) {\n color = decomposeColor(color);\n value = clampWrapper(value);\n if (color.type === 'rgb' || color.type === 'hsl') {\n color.type += 'a';\n }\n if (color.type === 'color') {\n color.values[3] = `/${value}`;\n } else {\n color.values[3] = value;\n }\n return recomposeColor(color);\n}\nfunction private_safeAlpha(color, value, warning) {\n try {\n return alpha(color, value);\n } catch (error) {\n if (warning && process.env.NODE_ENV !== 'production') {\n console.warn(warning);\n }\n return color;\n }\n}\n\n/**\n * Darkens a color.\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\nfunction darken(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clampWrapper(coefficient);\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] *= 1 - coefficient;\n } else if (color.type.indexOf('rgb') !== -1 || color.type.indexOf('color') !== -1) {\n for (let i = 0; i < 3; i += 1) {\n color.values[i] *= 1 - coefficient;\n }\n }\n return recomposeColor(color);\n}\nfunction private_safeDarken(color, coefficient, warning) {\n try {\n return darken(color, coefficient);\n } catch (error) {\n if (warning && process.env.NODE_ENV !== 'production') {\n console.warn(warning);\n }\n return color;\n }\n}\n\n/**\n * Lightens a color.\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\nfunction lighten(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clampWrapper(coefficient);\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] += (100 - color.values[2]) * coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (let i = 0; i < 3; i += 1) {\n color.values[i] += (255 - color.values[i]) * coefficient;\n }\n } else if (color.type.indexOf('color') !== -1) {\n for (let i = 0; i < 3; i += 1) {\n color.values[i] += (1 - color.values[i]) * coefficient;\n }\n }\n return recomposeColor(color);\n}\nfunction private_safeLighten(color, coefficient, warning) {\n try {\n return lighten(color, coefficient);\n } catch (error) {\n if (warning && process.env.NODE_ENV !== 'production') {\n console.warn(warning);\n }\n return color;\n }\n}\n\n/**\n * Darken or lighten a color, depending on its luminance.\n * Light colors are darkened, dark colors are lightened.\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()\n * @param {number} coefficient=0.15 - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\nfunction emphasize(color, coefficient = 0.15) {\n return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);\n}\nfunction private_safeEmphasize(color, coefficient, warning) {\n try {\n return emphasize(color, coefficient);\n } catch (error) {\n if (warning && process.env.NODE_ENV !== 'production') {\n console.warn(warning);\n }\n return color;\n }\n}\n\n/**\n * Blend a transparent overlay color with a background color, resulting in a single\n * RGB color.\n * @param {string} background - CSS color\n * @param {string} overlay - CSS color\n * @param {number} opacity - Opacity multiplier in the range 0 - 1\n * @param {number} [gamma=1.0] - Gamma correction factor. For gamma-correct blending, 2.2 is usual.\n */\nfunction blend(background, overlay, opacity, gamma = 1.0) {\n const blendChannel = (b, o) => Math.round((b ** (1 / gamma) * (1 - opacity) + o ** (1 / gamma) * opacity) ** gamma);\n const backgroundColor = decomposeColor(background);\n const overlayColor = decomposeColor(overlay);\n const rgb = [blendChannel(backgroundColor.values[0], overlayColor.values[0]), blendChannel(backgroundColor.values[1], overlayColor.values[1]), blendChannel(backgroundColor.values[2], overlayColor.values[2])];\n return recomposeColor({\n type: 'rgb',\n values: rgb\n });\n}","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = createStyled;\nexports.shouldForwardProp = shouldForwardProp;\nexports.systemDefaultTheme = void 0;\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\nvar _objectWithoutPropertiesLoose2 = _interopRequireDefault(require(\"@babel/runtime/helpers/objectWithoutPropertiesLoose\"));\nvar _styledEngine = _interopRequireWildcard(require(\"@mui/styled-engine\"));\nvar _deepmerge = require(\"@mui/utils/deepmerge\");\nvar _capitalize = _interopRequireDefault(require(\"@mui/utils/capitalize\"));\nvar _getDisplayName = _interopRequireDefault(require(\"@mui/utils/getDisplayName\"));\nvar _createTheme = _interopRequireDefault(require(\"./createTheme\"));\nvar _styleFunctionSx = _interopRequireDefault(require(\"./styleFunctionSx\"));\nconst _excluded = [\"ownerState\"],\n _excluded2 = [\"variants\"],\n _excluded3 = [\"name\", \"slot\", \"skipVariantsResolver\", \"skipSx\", \"overridesResolver\"];\n/* eslint-disable no-underscore-dangle */\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }\nfunction isEmpty(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// https://github.com/emotion-js/emotion/blob/26ded6109fcd8ca9875cc2ce4564fee678a3f3c5/packages/styled/src/utils.js#L40\nfunction isStringTag(tag) {\n return typeof tag === 'string' &&\n // 96 is one less than the char code\n // for \"a\" so this is checking that\n // it's a lowercase character\n tag.charCodeAt(0) > 96;\n}\n\n// Update /system/styled/#api in case if this changes\nfunction shouldForwardProp(prop) {\n return prop !== 'ownerState' && prop !== 'theme' && prop !== 'sx' && prop !== 'as';\n}\nconst systemDefaultTheme = exports.systemDefaultTheme = (0, _createTheme.default)();\nconst lowercaseFirstLetter = string => {\n if (!string) {\n return string;\n }\n return string.charAt(0).toLowerCase() + string.slice(1);\n};\nfunction resolveTheme({\n defaultTheme,\n theme,\n themeId\n}) {\n return isEmpty(theme) ? defaultTheme : theme[themeId] || theme;\n}\nfunction defaultOverridesResolver(slot) {\n if (!slot) {\n return null;\n }\n return (props, styles) => styles[slot];\n}\nfunction processStyleArg(callableStyle, _ref) {\n let {\n ownerState\n } = _ref,\n props = (0, _objectWithoutPropertiesLoose2.default)(_ref, _excluded);\n const resolvedStylesArg = typeof callableStyle === 'function' ? callableStyle((0, _extends2.default)({\n ownerState\n }, props)) : callableStyle;\n if (Array.isArray(resolvedStylesArg)) {\n return resolvedStylesArg.flatMap(resolvedStyle => processStyleArg(resolvedStyle, (0, _extends2.default)({\n ownerState\n }, props)));\n }\n if (!!resolvedStylesArg && typeof resolvedStylesArg === 'object' && Array.isArray(resolvedStylesArg.variants)) {\n const {\n variants = []\n } = resolvedStylesArg,\n otherStyles = (0, _objectWithoutPropertiesLoose2.default)(resolvedStylesArg, _excluded2);\n let result = otherStyles;\n variants.forEach(variant => {\n let isMatch = true;\n if (typeof variant.props === 'function') {\n isMatch = variant.props((0, _extends2.default)({\n ownerState\n }, props, ownerState));\n } else {\n Object.keys(variant.props).forEach(key => {\n if ((ownerState == null ? void 0 : ownerState[key]) !== variant.props[key] && props[key] !== variant.props[key]) {\n isMatch = false;\n }\n });\n }\n if (isMatch) {\n if (!Array.isArray(result)) {\n result = [result];\n }\n result.push(typeof variant.style === 'function' ? variant.style((0, _extends2.default)({\n ownerState\n }, props, ownerState)) : variant.style);\n }\n });\n return result;\n }\n return resolvedStylesArg;\n}\nfunction createStyled(input = {}) {\n const {\n themeId,\n defaultTheme = systemDefaultTheme,\n rootShouldForwardProp = shouldForwardProp,\n slotShouldForwardProp = shouldForwardProp\n } = input;\n const systemSx = props => {\n return (0, _styleFunctionSx.default)((0, _extends2.default)({}, props, {\n theme: resolveTheme((0, _extends2.default)({}, props, {\n defaultTheme,\n themeId\n }))\n }));\n };\n systemSx.__mui_systemSx = true;\n return (tag, inputOptions = {}) => {\n // Filter out the `sx` style function from the previous styled component to prevent unnecessary styles generated by the composite components.\n (0, _styledEngine.internal_processStyles)(tag, styles => styles.filter(style => !(style != null && style.__mui_systemSx)));\n const {\n name: componentName,\n slot: componentSlot,\n skipVariantsResolver: inputSkipVariantsResolver,\n skipSx: inputSkipSx,\n // TODO v6: remove `lowercaseFirstLetter()` in the next major release\n // For more details: https://github.com/mui/material-ui/pull/37908\n overridesResolver = defaultOverridesResolver(lowercaseFirstLetter(componentSlot))\n } = inputOptions,\n options = (0, _objectWithoutPropertiesLoose2.default)(inputOptions, _excluded3);\n\n // if skipVariantsResolver option is defined, take the value, otherwise, true for root and false for other slots.\n const skipVariantsResolver = inputSkipVariantsResolver !== undefined ? inputSkipVariantsResolver :\n // TODO v6: remove `Root` in the next major release\n // For more details: https://github.com/mui/material-ui/pull/37908\n componentSlot && componentSlot !== 'Root' && componentSlot !== 'root' || false;\n const skipSx = inputSkipSx || false;\n let label;\n if (process.env.NODE_ENV !== 'production') {\n if (componentName) {\n // TODO v6: remove `lowercaseFirstLetter()` in the next major release\n // For more details: https://github.com/mui/material-ui/pull/37908\n label = `${componentName}-${lowercaseFirstLetter(componentSlot || 'Root')}`;\n }\n }\n let shouldForwardPropOption = shouldForwardProp;\n\n // TODO v6: remove `Root` in the next major release\n // For more details: https://github.com/mui/material-ui/pull/37908\n if (componentSlot === 'Root' || componentSlot === 'root') {\n shouldForwardPropOption = rootShouldForwardProp;\n } else if (componentSlot) {\n // any other slot specified\n shouldForwardPropOption = slotShouldForwardProp;\n } else if (isStringTag(tag)) {\n // for string (html) tag, preserve the behavior in emotion & styled-components.\n shouldForwardPropOption = undefined;\n }\n const defaultStyledResolver = (0, _styledEngine.default)(tag, (0, _extends2.default)({\n shouldForwardProp: shouldForwardPropOption,\n label\n }, options));\n const transformStyleArg = stylesArg => {\n // On the server Emotion doesn't use React.forwardRef for creating components, so the created\n // component stays as a function. This condition makes sure that we do not interpolate functions\n // which are basically components used as a selectors.\n if (typeof stylesArg === 'function' && stylesArg.__emotion_real !== stylesArg || (0, _deepmerge.isPlainObject)(stylesArg)) {\n return props => processStyleArg(stylesArg, (0, _extends2.default)({}, props, {\n theme: resolveTheme({\n theme: props.theme,\n defaultTheme,\n themeId\n })\n }));\n }\n return stylesArg;\n };\n const muiStyledResolver = (styleArg, ...expressions) => {\n let transformedStyleArg = transformStyleArg(styleArg);\n const expressionsWithDefaultTheme = expressions ? expressions.map(transformStyleArg) : [];\n if (componentName && overridesResolver) {\n expressionsWithDefaultTheme.push(props => {\n const theme = resolveTheme((0, _extends2.default)({}, props, {\n defaultTheme,\n themeId\n }));\n if (!theme.components || !theme.components[componentName] || !theme.components[componentName].styleOverrides) {\n return null;\n }\n const styleOverrides = theme.components[componentName].styleOverrides;\n const resolvedStyleOverrides = {};\n // TODO: v7 remove iteration and use `resolveStyleArg(styleOverrides[slot])` directly\n Object.entries(styleOverrides).forEach(([slotKey, slotStyle]) => {\n resolvedStyleOverrides[slotKey] = processStyleArg(slotStyle, (0, _extends2.default)({}, props, {\n theme\n }));\n });\n return overridesResolver(props, resolvedStyleOverrides);\n });\n }\n if (componentName && !skipVariantsResolver) {\n expressionsWithDefaultTheme.push(props => {\n var _theme$components;\n const theme = resolveTheme((0, _extends2.default)({}, props, {\n defaultTheme,\n themeId\n }));\n const themeVariants = theme == null || (_theme$components = theme.components) == null || (_theme$components = _theme$components[componentName]) == null ? void 0 : _theme$components.variants;\n return processStyleArg({\n variants: themeVariants\n }, (0, _extends2.default)({}, props, {\n theme\n }));\n });\n }\n if (!skipSx) {\n expressionsWithDefaultTheme.push(systemSx);\n }\n const numOfCustomFnsApplied = expressionsWithDefaultTheme.length - expressions.length;\n if (Array.isArray(styleArg) && numOfCustomFnsApplied > 0) {\n const placeholders = new Array(numOfCustomFnsApplied).fill('');\n // If the type is array, than we need to add placeholders in the template for the overrides, variants and the sx styles.\n transformedStyleArg = [...styleArg, ...placeholders];\n transformedStyleArg.raw = [...styleArg.raw, ...placeholders];\n }\n const Component = defaultStyledResolver(transformedStyleArg, ...expressionsWithDefaultTheme);\n if (process.env.NODE_ENV !== 'production') {\n let displayName;\n if (componentName) {\n displayName = `${componentName}${(0, _capitalize.default)(componentSlot || '')}`;\n }\n if (displayName === undefined) {\n displayName = `Styled(${(0, _getDisplayName.default)(tag)})`;\n }\n Component.displayName = displayName;\n }\n if (tag.muiName) {\n Component.muiName = tag.muiName;\n }\n return Component;\n };\n if (defaultStyledResolver.withConfig) {\n muiStyledResolver.withConfig = defaultStyledResolver.withConfig;\n }\n return muiStyledResolver;\n };\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport PropTypes from 'prop-types';\nimport deepmerge from '@mui/utils/deepmerge';\nimport merge from './merge';\n\n// The breakpoint **start** at this value.\n// For instance with the first breakpoint xs: [xs, sm[.\nexport const values = {\n xs: 0,\n // phone\n sm: 600,\n // tablet\n md: 900,\n // small laptop\n lg: 1200,\n // desktop\n xl: 1536 // large screen\n};\nconst defaultBreakpoints = {\n // Sorted ASC by size. That's important.\n // It can't be configured as it's used statically for propTypes.\n keys: ['xs', 'sm', 'md', 'lg', 'xl'],\n up: key => `@media (min-width:${values[key]}px)`\n};\nexport function handleBreakpoints(props, propValue, styleFromPropValue) {\n const theme = props.theme || {};\n if (Array.isArray(propValue)) {\n const themeBreakpoints = theme.breakpoints || defaultBreakpoints;\n return propValue.reduce((acc, item, index) => {\n acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);\n return acc;\n }, {});\n }\n if (typeof propValue === 'object') {\n const themeBreakpoints = theme.breakpoints || defaultBreakpoints;\n return Object.keys(propValue).reduce((acc, breakpoint) => {\n // key is breakpoint\n if (Object.keys(themeBreakpoints.values || values).indexOf(breakpoint) !== -1) {\n const mediaKey = themeBreakpoints.up(breakpoint);\n acc[mediaKey] = styleFromPropValue(propValue[breakpoint], breakpoint);\n } else {\n const cssKey = breakpoint;\n acc[cssKey] = propValue[cssKey];\n }\n return acc;\n }, {});\n }\n const output = styleFromPropValue(propValue);\n return output;\n}\nfunction breakpoints(styleFunction) {\n // false positive\n // eslint-disable-next-line react/function-component-definition\n const newStyleFunction = props => {\n const theme = props.theme || {};\n const base = styleFunction(props);\n const themeBreakpoints = theme.breakpoints || defaultBreakpoints;\n const extended = themeBreakpoints.keys.reduce((acc, key) => {\n if (props[key]) {\n acc = acc || {};\n acc[themeBreakpoints.up(key)] = styleFunction(_extends({\n theme\n }, props[key]));\n }\n return acc;\n }, null);\n return merge(base, extended);\n };\n newStyleFunction.propTypes = process.env.NODE_ENV !== 'production' ? _extends({}, styleFunction.propTypes, {\n xs: PropTypes.object,\n sm: PropTypes.object,\n md: PropTypes.object,\n lg: PropTypes.object,\n xl: PropTypes.object\n }) : {};\n newStyleFunction.filterProps = ['xs', 'sm', 'md', 'lg', 'xl', ...styleFunction.filterProps];\n return newStyleFunction;\n}\nexport function createEmptyBreakpointObject(breakpointsInput = {}) {\n var _breakpointsInput$key;\n const breakpointsInOrder = (_breakpointsInput$key = breakpointsInput.keys) == null ? void 0 : _breakpointsInput$key.reduce((acc, key) => {\n const breakpointStyleKey = breakpointsInput.up(key);\n acc[breakpointStyleKey] = {};\n return acc;\n }, {});\n return breakpointsInOrder || {};\n}\nexport function removeUnusedBreakpoints(breakpointKeys, style) {\n return breakpointKeys.reduce((acc, key) => {\n const breakpointOutput = acc[key];\n const isBreakpointUnused = !breakpointOutput || Object.keys(breakpointOutput).length === 0;\n if (isBreakpointUnused) {\n delete acc[key];\n }\n return acc;\n }, style);\n}\nexport function mergeBreakpointsInOrder(breakpointsInput, ...styles) {\n const emptyBreakpoints = createEmptyBreakpointObject(breakpointsInput);\n const mergedOutput = [emptyBreakpoints, ...styles].reduce((prev, next) => deepmerge(prev, next), {});\n return removeUnusedBreakpoints(Object.keys(emptyBreakpoints), mergedOutput);\n}\n\n// compute base for responsive values; e.g.,\n// [1,2,3] => {xs: true, sm: true, md: true}\n// {xs: 1, sm: 2, md: 3} => {xs: true, sm: true, md: true}\nexport function computeBreakpointsBase(breakpointValues, themeBreakpoints) {\n // fixed value\n if (typeof breakpointValues !== 'object') {\n return {};\n }\n const base = {};\n const breakpointsKeys = Object.keys(themeBreakpoints);\n if (Array.isArray(breakpointValues)) {\n breakpointsKeys.forEach((breakpoint, i) => {\n if (i < breakpointValues.length) {\n base[breakpoint] = true;\n }\n });\n } else {\n breakpointsKeys.forEach(breakpoint => {\n if (breakpointValues[breakpoint] != null) {\n base[breakpoint] = true;\n }\n });\n }\n return base;\n}\nexport function resolveBreakpointValues({\n values: breakpointValues,\n breakpoints: themeBreakpoints,\n base: customBase\n}) {\n const base = customBase || computeBreakpointsBase(breakpointValues, themeBreakpoints);\n const keys = Object.keys(base);\n if (keys.length === 0) {\n return breakpointValues;\n }\n let previous;\n return keys.reduce((acc, breakpoint, i) => {\n if (Array.isArray(breakpointValues)) {\n acc[breakpoint] = breakpointValues[i] != null ? breakpointValues[i] : breakpointValues[previous];\n previous = i;\n } else if (typeof breakpointValues === 'object') {\n acc[breakpoint] = breakpointValues[breakpoint] != null ? breakpointValues[breakpoint] : breakpointValues[previous];\n previous = breakpoint;\n } else {\n acc[breakpoint] = breakpointValues;\n }\n return acc;\n }, {});\n}\nexport default breakpoints;","/**\n * A universal utility to style components with multiple color modes. Always use it from the theme object.\n * It works with:\n * - [Basic theme](https://mui.com/material-ui/customization/dark-mode/)\n * - [CSS theme variables](https://mui.com/material-ui/experimental-api/css-theme-variables/overview/)\n * - Zero-runtime engine\n *\n * Tips: Use an array over object spread and place `theme.applyStyles()` last.\n *\n * ✅ [{ background: '#e5e5e5' }, theme.applyStyles('dark', { background: '#1c1c1c' })]\n *\n * 🚫 { background: '#e5e5e5', ...theme.applyStyles('dark', { background: '#1c1c1c' })}\n *\n * @example\n * 1. using with `styled`:\n * ```jsx\n * const Component = styled('div')(({ theme }) => [\n * { background: '#e5e5e5' },\n * theme.applyStyles('dark', {\n * background: '#1c1c1c',\n * color: '#fff',\n * }),\n * ]);\n * ```\n *\n * @example\n * 2. using with `sx` prop:\n * ```jsx\n * [\n * { background: '#e5e5e5' },\n * theme.applyStyles('dark', {\n * background: '#1c1c1c',\n * color: '#fff',\n * }),\n * ]}\n * />\n * ```\n *\n * @example\n * 3. theming a component:\n * ```jsx\n * extendTheme({\n * components: {\n * MuiButton: {\n * styleOverrides: {\n * root: ({ theme }) => [\n * { background: '#e5e5e5' },\n * theme.applyStyles('dark', {\n * background: '#1c1c1c',\n * color: '#fff',\n * }),\n * ],\n * },\n * }\n * }\n * })\n *```\n */\nexport default function applyStyles(key, styles) {\n // @ts-expect-error this is 'any' type\n const theme = this;\n if (theme.vars && typeof theme.getColorSchemeSelector === 'function') {\n // If CssVarsProvider is used as a provider,\n // returns '* :where([data-mui-color-scheme=\"light|dark\"]) &'\n const selector = theme.getColorSchemeSelector(key).replace(/(\\[[^\\]]+\\])/, '*:where($1)');\n return {\n [selector]: styles\n };\n }\n if (theme.palette.mode === key) {\n return styles;\n }\n return {};\n}","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"values\", \"unit\", \"step\"];\n// Sorted ASC by size. That's important.\n// It can't be configured as it's used statically for propTypes.\nexport const breakpointKeys = ['xs', 'sm', 'md', 'lg', 'xl'];\nconst sortBreakpointsValues = values => {\n const breakpointsAsArray = Object.keys(values).map(key => ({\n key,\n val: values[key]\n })) || [];\n // Sort in ascending order\n breakpointsAsArray.sort((breakpoint1, breakpoint2) => breakpoint1.val - breakpoint2.val);\n return breakpointsAsArray.reduce((acc, obj) => {\n return _extends({}, acc, {\n [obj.key]: obj.val\n });\n }, {});\n};\n\n// Keep in mind that @media is inclusive by the CSS specification.\nexport default function createBreakpoints(breakpoints) {\n const {\n // The breakpoint **start** at this value.\n // For instance with the first breakpoint xs: [xs, sm).\n values = {\n xs: 0,\n // phone\n sm: 600,\n // tablet\n md: 900,\n // small laptop\n lg: 1200,\n // desktop\n xl: 1536 // large screen\n },\n unit = 'px',\n step = 5\n } = breakpoints,\n other = _objectWithoutPropertiesLoose(breakpoints, _excluded);\n const sortedValues = sortBreakpointsValues(values);\n const keys = Object.keys(sortedValues);\n function up(key) {\n const value = typeof values[key] === 'number' ? values[key] : key;\n return `@media (min-width:${value}${unit})`;\n }\n function down(key) {\n const value = typeof values[key] === 'number' ? values[key] : key;\n return `@media (max-width:${value - step / 100}${unit})`;\n }\n function between(start, end) {\n const endIndex = keys.indexOf(end);\n return `@media (min-width:${typeof values[start] === 'number' ? values[start] : start}${unit}) and ` + `(max-width:${(endIndex !== -1 && typeof values[keys[endIndex]] === 'number' ? values[keys[endIndex]] : end) - step / 100}${unit})`;\n }\n function only(key) {\n if (keys.indexOf(key) + 1 < keys.length) {\n return between(key, keys[keys.indexOf(key) + 1]);\n }\n return up(key);\n }\n function not(key) {\n // handle first and last key separately, for better readability\n const keyIndex = keys.indexOf(key);\n if (keyIndex === 0) {\n return up(keys[1]);\n }\n if (keyIndex === keys.length - 1) {\n return down(keys[keyIndex]);\n }\n return between(key, keys[keys.indexOf(key) + 1]).replace('@media', '@media not all and');\n }\n return _extends({\n keys,\n values: sortedValues,\n up,\n down,\n between,\n only,\n not,\n unit\n }, other);\n}","const shape = {\n borderRadius: 4\n};\nexport default shape;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"breakpoints\", \"palette\", \"spacing\", \"shape\"];\nimport deepmerge from '@mui/utils/deepmerge';\nimport createBreakpoints from './createBreakpoints';\nimport shape from './shape';\nimport createSpacing from './createSpacing';\nimport styleFunctionSx from '../styleFunctionSx/styleFunctionSx';\nimport defaultSxConfig from '../styleFunctionSx/defaultSxConfig';\nimport applyStyles from './applyStyles';\nfunction createTheme(options = {}, ...args) {\n const {\n breakpoints: breakpointsInput = {},\n palette: paletteInput = {},\n spacing: spacingInput,\n shape: shapeInput = {}\n } = options,\n other = _objectWithoutPropertiesLoose(options, _excluded);\n const breakpoints = createBreakpoints(breakpointsInput);\n const spacing = createSpacing(spacingInput);\n let muiTheme = deepmerge({\n breakpoints,\n direction: 'ltr',\n components: {},\n // Inject component definitions.\n palette: _extends({\n mode: 'light'\n }, paletteInput),\n spacing,\n shape: _extends({}, shape, shapeInput)\n }, other);\n muiTheme.applyStyles = applyStyles;\n muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);\n muiTheme.unstable_sxConfig = _extends({}, defaultSxConfig, other == null ? void 0 : other.unstable_sxConfig);\n muiTheme.unstable_sx = function sx(props) {\n return styleFunctionSx({\n sx: props,\n theme: this\n });\n };\n return muiTheme;\n}\nexport default createTheme;","import { createUnarySpacing } from '../spacing';\n\n// The different signatures imply different meaning for their arguments that can't be expressed structurally.\n// We express the difference with variable names.\n\nexport default function createSpacing(spacingInput = 8) {\n // Already transformed.\n if (spacingInput.mui) {\n return spacingInput;\n }\n\n // Material Design layouts are visually balanced. Most measurements align to an 8dp grid, which aligns both spacing and the overall layout.\n // Smaller components, such as icons, can align to a 4dp grid.\n // https://m2.material.io/design/layout/understanding-layout.html\n const transform = createUnarySpacing({\n spacing: spacingInput\n });\n const spacing = (...argsInput) => {\n if (process.env.NODE_ENV !== 'production') {\n if (!(argsInput.length <= 4)) {\n console.error(`MUI: Too many arguments provided, expected between 0 and 4, got ${argsInput.length}`);\n }\n }\n const args = argsInput.length === 0 ? [1] : argsInput;\n return args.map(argument => {\n const output = transform(argument);\n return typeof output === 'number' ? `${output}px` : output;\n }).join(' ');\n };\n spacing.mui = true;\n return spacing;\n}","import deepmerge from '@mui/utils/deepmerge';\nfunction merge(acc, item) {\n if (!item) {\n return acc;\n }\n return deepmerge(acc, item, {\n clone: false // No need to clone deep, it's way faster.\n });\n}\nexport default merge;","import responsivePropType from './responsivePropType';\nimport { handleBreakpoints } from './breakpoints';\nimport { getPath } from './style';\nimport merge from './merge';\nimport memoize from './memoize';\nconst properties = {\n m: 'margin',\n p: 'padding'\n};\nconst directions = {\n t: 'Top',\n r: 'Right',\n b: 'Bottom',\n l: 'Left',\n x: ['Left', 'Right'],\n y: ['Top', 'Bottom']\n};\nconst aliases = {\n marginX: 'mx',\n marginY: 'my',\n paddingX: 'px',\n paddingY: 'py'\n};\n\n// memoize() impact:\n// From 300,000 ops/sec\n// To 350,000 ops/sec\nconst getCssProperties = memoize(prop => {\n // It's not a shorthand notation.\n if (prop.length > 2) {\n if (aliases[prop]) {\n prop = aliases[prop];\n } else {\n return [prop];\n }\n }\n const [a, b] = prop.split('');\n const property = properties[a];\n const direction = directions[b] || '';\n return Array.isArray(direction) ? direction.map(dir => property + dir) : [property + direction];\n});\nexport const marginKeys = ['m', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'marginInline', 'marginInlineStart', 'marginInlineEnd', 'marginBlock', 'marginBlockStart', 'marginBlockEnd'];\nexport const paddingKeys = ['p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY', 'paddingInline', 'paddingInlineStart', 'paddingInlineEnd', 'paddingBlock', 'paddingBlockStart', 'paddingBlockEnd'];\nconst spacingKeys = [...marginKeys, ...paddingKeys];\nexport function createUnaryUnit(theme, themeKey, defaultValue, propName) {\n var _getPath;\n const themeSpacing = (_getPath = getPath(theme, themeKey, false)) != null ? _getPath : defaultValue;\n if (typeof themeSpacing === 'number') {\n return abs => {\n if (typeof abs === 'string') {\n return abs;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (typeof abs !== 'number') {\n console.error(`MUI: Expected ${propName} argument to be a number or a string, got ${abs}.`);\n }\n }\n return themeSpacing * abs;\n };\n }\n if (Array.isArray(themeSpacing)) {\n return abs => {\n if (typeof abs === 'string') {\n return abs;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!Number.isInteger(abs)) {\n console.error([`MUI: The \\`theme.${themeKey}\\` array type cannot be combined with non integer values.` + `You should either use an integer value that can be used as index, or define the \\`theme.${themeKey}\\` as a number.`].join('\\n'));\n } else if (abs > themeSpacing.length - 1) {\n console.error([`MUI: The value provided (${abs}) overflows.`, `The supported values are: ${JSON.stringify(themeSpacing)}.`, `${abs} > ${themeSpacing.length - 1}, you need to add the missing values.`].join('\\n'));\n }\n }\n return themeSpacing[abs];\n };\n }\n if (typeof themeSpacing === 'function') {\n return themeSpacing;\n }\n if (process.env.NODE_ENV !== 'production') {\n console.error([`MUI: The \\`theme.${themeKey}\\` value (${themeSpacing}) is invalid.`, 'It should be a number, an array or a function.'].join('\\n'));\n }\n return () => undefined;\n}\nexport function createUnarySpacing(theme) {\n return createUnaryUnit(theme, 'spacing', 8, 'spacing');\n}\nexport function getValue(transformer, propValue) {\n if (typeof propValue === 'string' || propValue == null) {\n return propValue;\n }\n const abs = Math.abs(propValue);\n const transformed = transformer(abs);\n if (propValue >= 0) {\n return transformed;\n }\n if (typeof transformed === 'number') {\n return -transformed;\n }\n return `-${transformed}`;\n}\nexport function getStyleFromPropValue(cssProperties, transformer) {\n return propValue => cssProperties.reduce((acc, cssProperty) => {\n acc[cssProperty] = getValue(transformer, propValue);\n return acc;\n }, {});\n}\nfunction resolveCssProperty(props, keys, prop, transformer) {\n // Using a hash computation over an array iteration could be faster, but with only 28 items,\n // it's doesn't worth the bundle size.\n if (keys.indexOf(prop) === -1) {\n return null;\n }\n const cssProperties = getCssProperties(prop);\n const styleFromPropValue = getStyleFromPropValue(cssProperties, transformer);\n const propValue = props[prop];\n return handleBreakpoints(props, propValue, styleFromPropValue);\n}\nfunction style(props, keys) {\n const transformer = createUnarySpacing(props.theme);\n return Object.keys(props).map(prop => resolveCssProperty(props, keys, prop, transformer)).reduce(merge, {});\n}\nexport function margin(props) {\n return style(props, marginKeys);\n}\nmargin.propTypes = process.env.NODE_ENV !== 'production' ? marginKeys.reduce((obj, key) => {\n obj[key] = responsivePropType;\n return obj;\n}, {}) : {};\nmargin.filterProps = marginKeys;\nexport function padding(props) {\n return style(props, paddingKeys);\n}\npadding.propTypes = process.env.NODE_ENV !== 'production' ? paddingKeys.reduce((obj, key) => {\n obj[key] = responsivePropType;\n return obj;\n}, {}) : {};\npadding.filterProps = paddingKeys;\nfunction spacing(props) {\n return style(props, spacingKeys);\n}\nspacing.propTypes = process.env.NODE_ENV !== 'production' ? spacingKeys.reduce((obj, key) => {\n obj[key] = responsivePropType;\n return obj;\n}, {}) : {};\nspacing.filterProps = spacingKeys;\nexport default spacing;","export default function memoize(fn) {\n const cache = {};\n return arg => {\n if (cache[arg] === undefined) {\n cache[arg] = fn(arg);\n }\n return cache[arg];\n };\n}","import capitalize from '@mui/utils/capitalize';\nimport responsivePropType from './responsivePropType';\nimport { handleBreakpoints } from './breakpoints';\nexport function getPath(obj, path, checkVars = true) {\n if (!path || typeof path !== 'string') {\n return null;\n }\n\n // Check if CSS variables are used\n if (obj && obj.vars && checkVars) {\n const val = `vars.${path}`.split('.').reduce((acc, item) => acc && acc[item] ? acc[item] : null, obj);\n if (val != null) {\n return val;\n }\n }\n return path.split('.').reduce((acc, item) => {\n if (acc && acc[item] != null) {\n return acc[item];\n }\n return null;\n }, obj);\n}\nexport function getStyleValue(themeMapping, transform, propValueFinal, userValue = propValueFinal) {\n let value;\n if (typeof themeMapping === 'function') {\n value = themeMapping(propValueFinal);\n } else if (Array.isArray(themeMapping)) {\n value = themeMapping[propValueFinal] || userValue;\n } else {\n value = getPath(themeMapping, propValueFinal) || userValue;\n }\n if (transform) {\n value = transform(value, userValue, themeMapping);\n }\n return value;\n}\nfunction style(options) {\n const {\n prop,\n cssProperty = options.prop,\n themeKey,\n transform\n } = options;\n\n // false positive\n // eslint-disable-next-line react/function-component-definition\n const fn = props => {\n if (props[prop] == null) {\n return null;\n }\n const propValue = props[prop];\n const theme = props.theme;\n const themeMapping = getPath(theme, themeKey) || {};\n const styleFromPropValue = propValueFinal => {\n let value = getStyleValue(themeMapping, transform, propValueFinal);\n if (propValueFinal === value && typeof propValueFinal === 'string') {\n // Haven't found value\n value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal);\n }\n if (cssProperty === false) {\n return value;\n }\n return {\n [cssProperty]: value\n };\n };\n return handleBreakpoints(props, propValue, styleFromPropValue);\n };\n fn.propTypes = process.env.NODE_ENV !== 'production' ? {\n [prop]: responsivePropType\n } : {};\n fn.filterProps = [prop];\n return fn;\n}\nexport default style;","import merge from './merge';\nfunction compose(...styles) {\n const handlers = styles.reduce((acc, style) => {\n style.filterProps.forEach(prop => {\n acc[prop] = style;\n });\n return acc;\n }, {});\n\n // false positive\n // eslint-disable-next-line react/function-component-definition\n const fn = props => {\n return Object.keys(props).reduce((acc, prop) => {\n if (handlers[prop]) {\n return merge(acc, handlers[prop](props));\n }\n return acc;\n }, {});\n };\n fn.propTypes = process.env.NODE_ENV !== 'production' ? styles.reduce((acc, style) => Object.assign(acc, style.propTypes), {}) : {};\n fn.filterProps = styles.reduce((acc, style) => acc.concat(style.filterProps), []);\n return fn;\n}\nexport default compose;","import responsivePropType from './responsivePropType';\nimport style from './style';\nimport compose from './compose';\nimport { createUnaryUnit, getValue } from './spacing';\nimport { handleBreakpoints } from './breakpoints';\nexport function borderTransform(value) {\n if (typeof value !== 'number') {\n return value;\n }\n return `${value}px solid`;\n}\nfunction createBorderStyle(prop, transform) {\n return style({\n prop,\n themeKey: 'borders',\n transform\n });\n}\nexport const border = createBorderStyle('border', borderTransform);\nexport const borderTop = createBorderStyle('borderTop', borderTransform);\nexport const borderRight = createBorderStyle('borderRight', borderTransform);\nexport const borderBottom = createBorderStyle('borderBottom', borderTransform);\nexport const borderLeft = createBorderStyle('borderLeft', borderTransform);\nexport const borderColor = createBorderStyle('borderColor');\nexport const borderTopColor = createBorderStyle('borderTopColor');\nexport const borderRightColor = createBorderStyle('borderRightColor');\nexport const borderBottomColor = createBorderStyle('borderBottomColor');\nexport const borderLeftColor = createBorderStyle('borderLeftColor');\nexport const outline = createBorderStyle('outline', borderTransform);\nexport const outlineColor = createBorderStyle('outlineColor');\n\n// false positive\n// eslint-disable-next-line react/function-component-definition\nexport const borderRadius = props => {\n if (props.borderRadius !== undefined && props.borderRadius !== null) {\n const transformer = createUnaryUnit(props.theme, 'shape.borderRadius', 4, 'borderRadius');\n const styleFromPropValue = propValue => ({\n borderRadius: getValue(transformer, propValue)\n });\n return handleBreakpoints(props, props.borderRadius, styleFromPropValue);\n }\n return null;\n};\nborderRadius.propTypes = process.env.NODE_ENV !== 'production' ? {\n borderRadius: responsivePropType\n} : {};\nborderRadius.filterProps = ['borderRadius'];\nconst borders = compose(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderTopColor, borderRightColor, borderBottomColor, borderLeftColor, borderRadius, outline, outlineColor);\nexport default borders;","import style from './style';\nimport compose from './compose';\nimport { createUnaryUnit, getValue } from './spacing';\nimport { handleBreakpoints } from './breakpoints';\nimport responsivePropType from './responsivePropType';\n\n// false positive\n// eslint-disable-next-line react/function-component-definition\nexport const gap = props => {\n if (props.gap !== undefined && props.gap !== null) {\n const transformer = createUnaryUnit(props.theme, 'spacing', 8, 'gap');\n const styleFromPropValue = propValue => ({\n gap: getValue(transformer, propValue)\n });\n return handleBreakpoints(props, props.gap, styleFromPropValue);\n }\n return null;\n};\ngap.propTypes = process.env.NODE_ENV !== 'production' ? {\n gap: responsivePropType\n} : {};\ngap.filterProps = ['gap'];\n\n// false positive\n// eslint-disable-next-line react/function-component-definition\nexport const columnGap = props => {\n if (props.columnGap !== undefined && props.columnGap !== null) {\n const transformer = createUnaryUnit(props.theme, 'spacing', 8, 'columnGap');\n const styleFromPropValue = propValue => ({\n columnGap: getValue(transformer, propValue)\n });\n return handleBreakpoints(props, props.columnGap, styleFromPropValue);\n }\n return null;\n};\ncolumnGap.propTypes = process.env.NODE_ENV !== 'production' ? {\n columnGap: responsivePropType\n} : {};\ncolumnGap.filterProps = ['columnGap'];\n\n// false positive\n// eslint-disable-next-line react/function-component-definition\nexport const rowGap = props => {\n if (props.rowGap !== undefined && props.rowGap !== null) {\n const transformer = createUnaryUnit(props.theme, 'spacing', 8, 'rowGap');\n const styleFromPropValue = propValue => ({\n rowGap: getValue(transformer, propValue)\n });\n return handleBreakpoints(props, props.rowGap, styleFromPropValue);\n }\n return null;\n};\nrowGap.propTypes = process.env.NODE_ENV !== 'production' ? {\n rowGap: responsivePropType\n} : {};\nrowGap.filterProps = ['rowGap'];\nexport const gridColumn = style({\n prop: 'gridColumn'\n});\nexport const gridRow = style({\n prop: 'gridRow'\n});\nexport const gridAutoFlow = style({\n prop: 'gridAutoFlow'\n});\nexport const gridAutoColumns = style({\n prop: 'gridAutoColumns'\n});\nexport const gridAutoRows = style({\n prop: 'gridAutoRows'\n});\nexport const gridTemplateColumns = style({\n prop: 'gridTemplateColumns'\n});\nexport const gridTemplateRows = style({\n prop: 'gridTemplateRows'\n});\nexport const gridTemplateAreas = style({\n prop: 'gridTemplateAreas'\n});\nexport const gridArea = style({\n prop: 'gridArea'\n});\nconst grid = compose(gap, columnGap, rowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea);\nexport default grid;","import style from './style';\nimport compose from './compose';\nexport function paletteTransform(value, userValue) {\n if (userValue === 'grey') {\n return userValue;\n }\n return value;\n}\nexport const color = style({\n prop: 'color',\n themeKey: 'palette',\n transform: paletteTransform\n});\nexport const bgcolor = style({\n prop: 'bgcolor',\n cssProperty: 'backgroundColor',\n themeKey: 'palette',\n transform: paletteTransform\n});\nexport const backgroundColor = style({\n prop: 'backgroundColor',\n themeKey: 'palette',\n transform: paletteTransform\n});\nconst palette = compose(color, bgcolor, backgroundColor);\nexport default palette;","import style from './style';\nimport compose from './compose';\nimport { handleBreakpoints, values as breakpointsValues } from './breakpoints';\nexport function sizingTransform(value) {\n return value <= 1 && value !== 0 ? `${value * 100}%` : value;\n}\nexport const width = style({\n prop: 'width',\n transform: sizingTransform\n});\nexport const maxWidth = props => {\n if (props.maxWidth !== undefined && props.maxWidth !== null) {\n const styleFromPropValue = propValue => {\n var _props$theme, _props$theme2;\n const breakpoint = ((_props$theme = props.theme) == null || (_props$theme = _props$theme.breakpoints) == null || (_props$theme = _props$theme.values) == null ? void 0 : _props$theme[propValue]) || breakpointsValues[propValue];\n if (!breakpoint) {\n return {\n maxWidth: sizingTransform(propValue)\n };\n }\n if (((_props$theme2 = props.theme) == null || (_props$theme2 = _props$theme2.breakpoints) == null ? void 0 : _props$theme2.unit) !== 'px') {\n return {\n maxWidth: `${breakpoint}${props.theme.breakpoints.unit}`\n };\n }\n return {\n maxWidth: breakpoint\n };\n };\n return handleBreakpoints(props, props.maxWidth, styleFromPropValue);\n }\n return null;\n};\nmaxWidth.filterProps = ['maxWidth'];\nexport const minWidth = style({\n prop: 'minWidth',\n transform: sizingTransform\n});\nexport const height = style({\n prop: 'height',\n transform: sizingTransform\n});\nexport const maxHeight = style({\n prop: 'maxHeight',\n transform: sizingTransform\n});\nexport const minHeight = style({\n prop: 'minHeight',\n transform: sizingTransform\n});\nexport const sizeWidth = style({\n prop: 'size',\n cssProperty: 'width',\n transform: sizingTransform\n});\nexport const sizeHeight = style({\n prop: 'size',\n cssProperty: 'height',\n transform: sizingTransform\n});\nexport const boxSizing = style({\n prop: 'boxSizing'\n});\nconst sizing = compose(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing);\nexport default sizing;","import { padding, margin } from '../spacing';\nimport { borderRadius, borderTransform } from '../borders';\nimport { gap, rowGap, columnGap } from '../cssGrid';\nimport { paletteTransform } from '../palette';\nimport { maxWidth, sizingTransform } from '../sizing';\nconst defaultSxConfig = {\n // borders\n border: {\n themeKey: 'borders',\n transform: borderTransform\n },\n borderTop: {\n themeKey: 'borders',\n transform: borderTransform\n },\n borderRight: {\n themeKey: 'borders',\n transform: borderTransform\n },\n borderBottom: {\n themeKey: 'borders',\n transform: borderTransform\n },\n borderLeft: {\n themeKey: 'borders',\n transform: borderTransform\n },\n borderColor: {\n themeKey: 'palette'\n },\n borderTopColor: {\n themeKey: 'palette'\n },\n borderRightColor: {\n themeKey: 'palette'\n },\n borderBottomColor: {\n themeKey: 'palette'\n },\n borderLeftColor: {\n themeKey: 'palette'\n },\n outline: {\n themeKey: 'borders',\n transform: borderTransform\n },\n outlineColor: {\n themeKey: 'palette'\n },\n borderRadius: {\n themeKey: 'shape.borderRadius',\n style: borderRadius\n },\n // palette\n color: {\n themeKey: 'palette',\n transform: paletteTransform\n },\n bgcolor: {\n themeKey: 'palette',\n cssProperty: 'backgroundColor',\n transform: paletteTransform\n },\n backgroundColor: {\n themeKey: 'palette',\n transform: paletteTransform\n },\n // spacing\n p: {\n style: padding\n },\n pt: {\n style: padding\n },\n pr: {\n style: padding\n },\n pb: {\n style: padding\n },\n pl: {\n style: padding\n },\n px: {\n style: padding\n },\n py: {\n style: padding\n },\n padding: {\n style: padding\n },\n paddingTop: {\n style: padding\n },\n paddingRight: {\n style: padding\n },\n paddingBottom: {\n style: padding\n },\n paddingLeft: {\n style: padding\n },\n paddingX: {\n style: padding\n },\n paddingY: {\n style: padding\n },\n paddingInline: {\n style: padding\n },\n paddingInlineStart: {\n style: padding\n },\n paddingInlineEnd: {\n style: padding\n },\n paddingBlock: {\n style: padding\n },\n paddingBlockStart: {\n style: padding\n },\n paddingBlockEnd: {\n style: padding\n },\n m: {\n style: margin\n },\n mt: {\n style: margin\n },\n mr: {\n style: margin\n },\n mb: {\n style: margin\n },\n ml: {\n style: margin\n },\n mx: {\n style: margin\n },\n my: {\n style: margin\n },\n margin: {\n style: margin\n },\n marginTop: {\n style: margin\n },\n marginRight: {\n style: margin\n },\n marginBottom: {\n style: margin\n },\n marginLeft: {\n style: margin\n },\n marginX: {\n style: margin\n },\n marginY: {\n style: margin\n },\n marginInline: {\n style: margin\n },\n marginInlineStart: {\n style: margin\n },\n marginInlineEnd: {\n style: margin\n },\n marginBlock: {\n style: margin\n },\n marginBlockStart: {\n style: margin\n },\n marginBlockEnd: {\n style: margin\n },\n // display\n displayPrint: {\n cssProperty: false,\n transform: value => ({\n '@media print': {\n display: value\n }\n })\n },\n display: {},\n overflow: {},\n textOverflow: {},\n visibility: {},\n whiteSpace: {},\n // flexbox\n flexBasis: {},\n flexDirection: {},\n flexWrap: {},\n justifyContent: {},\n alignItems: {},\n alignContent: {},\n order: {},\n flex: {},\n flexGrow: {},\n flexShrink: {},\n alignSelf: {},\n justifyItems: {},\n justifySelf: {},\n // grid\n gap: {\n style: gap\n },\n rowGap: {\n style: rowGap\n },\n columnGap: {\n style: columnGap\n },\n gridColumn: {},\n gridRow: {},\n gridAutoFlow: {},\n gridAutoColumns: {},\n gridAutoRows: {},\n gridTemplateColumns: {},\n gridTemplateRows: {},\n gridTemplateAreas: {},\n gridArea: {},\n // positions\n position: {},\n zIndex: {\n themeKey: 'zIndex'\n },\n top: {},\n right: {},\n bottom: {},\n left: {},\n // shadows\n boxShadow: {\n themeKey: 'shadows'\n },\n // sizing\n width: {\n transform: sizingTransform\n },\n maxWidth: {\n style: maxWidth\n },\n minWidth: {\n transform: sizingTransform\n },\n height: {\n transform: sizingTransform\n },\n maxHeight: {\n transform: sizingTransform\n },\n minHeight: {\n transform: sizingTransform\n },\n boxSizing: {},\n // typography\n fontFamily: {\n themeKey: 'typography'\n },\n fontSize: {\n themeKey: 'typography'\n },\n fontStyle: {\n themeKey: 'typography'\n },\n fontWeight: {\n themeKey: 'typography'\n },\n letterSpacing: {},\n textTransform: {},\n lineHeight: {},\n textAlign: {},\n typography: {\n cssProperty: false,\n themeKey: 'typography'\n }\n};\nexport default defaultSxConfig;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"sx\"];\nimport { isPlainObject } from '@mui/utils/deepmerge';\nimport defaultSxConfig from './defaultSxConfig';\nconst splitProps = props => {\n var _props$theme$unstable, _props$theme;\n const result = {\n systemProps: {},\n otherProps: {}\n };\n const config = (_props$theme$unstable = props == null || (_props$theme = props.theme) == null ? void 0 : _props$theme.unstable_sxConfig) != null ? _props$theme$unstable : defaultSxConfig;\n Object.keys(props).forEach(prop => {\n if (config[prop]) {\n result.systemProps[prop] = props[prop];\n } else {\n result.otherProps[prop] = props[prop];\n }\n });\n return result;\n};\nexport default function extendSxProp(props) {\n const {\n sx: inSx\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const {\n systemProps,\n otherProps\n } = splitProps(other);\n let finalSx;\n if (Array.isArray(inSx)) {\n finalSx = [systemProps, ...inSx];\n } else if (typeof inSx === 'function') {\n finalSx = (...args) => {\n const result = inSx(...args);\n if (!isPlainObject(result)) {\n return systemProps;\n }\n return _extends({}, systemProps, result);\n };\n } else {\n finalSx = _extends({}, systemProps, inSx);\n }\n return _extends({}, otherProps, {\n sx: finalSx\n });\n}","import capitalize from '@mui/utils/capitalize';\nimport merge from '../merge';\nimport { getPath, getStyleValue as getValue } from '../style';\nimport { handleBreakpoints, createEmptyBreakpointObject, removeUnusedBreakpoints } from '../breakpoints';\nimport defaultSxConfig from './defaultSxConfig';\nfunction objectsHaveSameKeys(...objects) {\n const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);\n const union = new Set(allKeys);\n return objects.every(object => union.size === Object.keys(object).length);\n}\nfunction callIfFn(maybeFn, arg) {\n return typeof maybeFn === 'function' ? maybeFn(arg) : maybeFn;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function unstable_createStyleFunctionSx() {\n function getThemeValue(prop, val, theme, config) {\n const props = {\n [prop]: val,\n theme\n };\n const options = config[prop];\n if (!options) {\n return {\n [prop]: val\n };\n }\n const {\n cssProperty = prop,\n themeKey,\n transform,\n style\n } = options;\n if (val == null) {\n return null;\n }\n\n // TODO v6: remove, see https://github.com/mui/material-ui/pull/38123\n if (themeKey === 'typography' && val === 'inherit') {\n return {\n [prop]: val\n };\n }\n const themeMapping = getPath(theme, themeKey) || {};\n if (style) {\n return style(props);\n }\n const styleFromPropValue = propValueFinal => {\n let value = getValue(themeMapping, transform, propValueFinal);\n if (propValueFinal === value && typeof propValueFinal === 'string') {\n // Haven't found value\n value = getValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal);\n }\n if (cssProperty === false) {\n return value;\n }\n return {\n [cssProperty]: value\n };\n };\n return handleBreakpoints(props, val, styleFromPropValue);\n }\n function styleFunctionSx(props) {\n var _theme$unstable_sxCon;\n const {\n sx,\n theme = {}\n } = props || {};\n if (!sx) {\n return null; // Emotion & styled-components will neglect null\n }\n const config = (_theme$unstable_sxCon = theme.unstable_sxConfig) != null ? _theme$unstable_sxCon : defaultSxConfig;\n\n /*\n * Receive `sxInput` as object or callback\n * and then recursively check keys & values to create media query object styles.\n * (the result will be used in `styled`)\n */\n function traverse(sxInput) {\n let sxObject = sxInput;\n if (typeof sxInput === 'function') {\n sxObject = sxInput(theme);\n } else if (typeof sxInput !== 'object') {\n // value\n return sxInput;\n }\n if (!sxObject) {\n return null;\n }\n const emptyBreakpoints = createEmptyBreakpointObject(theme.breakpoints);\n const breakpointsKeys = Object.keys(emptyBreakpoints);\n let css = emptyBreakpoints;\n Object.keys(sxObject).forEach(styleKey => {\n const value = callIfFn(sxObject[styleKey], theme);\n if (value !== null && value !== undefined) {\n if (typeof value === 'object') {\n if (config[styleKey]) {\n css = merge(css, getThemeValue(styleKey, value, theme, config));\n } else {\n const breakpointsValues = handleBreakpoints({\n theme\n }, value, x => ({\n [styleKey]: x\n }));\n if (objectsHaveSameKeys(breakpointsValues, value)) {\n css[styleKey] = styleFunctionSx({\n sx: value,\n theme\n });\n } else {\n css = merge(css, breakpointsValues);\n }\n }\n } else {\n css = merge(css, getThemeValue(styleKey, value, theme, config));\n }\n }\n });\n return removeUnusedBreakpoints(breakpointsKeys, css);\n }\n return Array.isArray(sx) ? sx.map(traverse) : traverse(sx);\n }\n return styleFunctionSx;\n}\nconst styleFunctionSx = unstable_createStyleFunctionSx();\nstyleFunctionSx.filterProps = ['sx'];\nexport default styleFunctionSx;","\"use strict\";\n'use client';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _styledEngine = require(\"@mui/styled-engine\");\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }\nfunction isObjectEmpty(obj) {\n return Object.keys(obj).length === 0;\n}\nfunction useTheme(defaultTheme = null) {\n const contextTheme = React.useContext(_styledEngine.ThemeContext);\n return !contextTheme || isObjectEmpty(contextTheme) ? defaultTheme : contextTheme;\n}\nvar _default = exports.default = useTheme;","import _formatMuiErrorMessage from \"@mui/utils/formatMuiErrorMessage\";\n// It should to be noted that this function isn't equivalent to `text-transform: capitalize`.\n//\n// A strict capitalization should uppercase the first letter of each word in the sentence.\n// We only handle the first word.\nexport default function capitalize(string) {\n if (typeof string !== 'string') {\n throw new Error(process.env.NODE_ENV !== \"production\" ? `MUI: \\`capitalize(string)\\` expects a string argument.` : _formatMuiErrorMessage(7));\n }\n return string.charAt(0).toUpperCase() + string.slice(1);\n}","function clamp(val, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {\n return Math.max(min, Math.min(val, max));\n}\nexport default clamp;","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js\nexport function isPlainObject(item) {\n if (typeof item !== 'object' || item === null) {\n return false;\n }\n const prototype = Object.getPrototypeOf(item);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in item) && !(Symbol.iterator in item);\n}\nfunction deepClone(source) {\n if (!isPlainObject(source)) {\n return source;\n }\n const output = {};\n Object.keys(source).forEach(key => {\n output[key] = deepClone(source[key]);\n });\n return output;\n}\nexport default function deepmerge(target, source, options = {\n clone: true\n}) {\n const output = options.clone ? _extends({}, target) : target;\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(key => {\n if (isPlainObject(source[key]) &&\n // Avoid prototype pollution\n Object.prototype.hasOwnProperty.call(target, key) && isPlainObject(target[key])) {\n // Since `output` is a clone of `target` and we have narrowed `target` in this block we can cast to the same type.\n output[key] = deepmerge(target[key], source[key], options);\n } else if (options.clone) {\n output[key] = isPlainObject(source[key]) ? deepClone(source[key]) : source[key];\n } else {\n output[key] = source[key];\n }\n });\n }\n return output;\n}","/**\n * WARNING: Don't import this directly.\n * Use `MuiError` from `@mui/internal-babel-macros/MuiError.macro` instead.\n * @param {number} code\n */\nexport default function formatMuiErrorMessage(code) {\n // Apply babel-plugin-transform-template-literals in loose mode\n // loose mode is safe if we're concatenating primitives\n // see https://babeljs.io/docs/en/babel-plugin-transform-template-literals#loose\n /* eslint-disable prefer-template */\n let url = 'https://mui.com/production-error/?code=' + code;\n for (let i = 1; i < arguments.length; i += 1) {\n // rest params over-transpile for this case\n // eslint-disable-next-line prefer-rest-params\n url += '&args[]=' + encodeURIComponent(arguments[i]);\n }\n return 'Minified MUI error #' + code + '; visit ' + url + ' for the full message.';\n /* eslint-enable prefer-template */\n}","import { ForwardRef, Memo } from 'react-is';\n\n// Simplified polyfill for IE11 support\n// https://github.com/JamesMGreene/Function.name/blob/58b314d4a983110c3682f1228f845d39ccca1817/Function.name.js#L3\nconst fnNameMatchRegex = /^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^(\\s/]*)\\s*/;\nexport function getFunctionName(fn) {\n const match = `${fn}`.match(fnNameMatchRegex);\n const name = match && match[1];\n return name || '';\n}\nfunction getFunctionComponentName(Component, fallback = '') {\n return Component.displayName || Component.name || getFunctionName(Component) || fallback;\n}\nfunction getWrappedName(outerType, innerType, wrapperName) {\n const functionName = getFunctionComponentName(innerType);\n return outerType.displayName || (functionName !== '' ? `${wrapperName}(${functionName})` : wrapperName);\n}\n\n/**\n * cherry-pick from\n * https://github.com/facebook/react/blob/769b1f270e1251d9dbdce0fcbd9e92e502d059b8/packages/shared/getComponentName.js\n * originally forked from recompose/getDisplayName with added IE11 support\n */\nexport default function getDisplayName(Component) {\n if (Component == null) {\n return undefined;\n }\n if (typeof Component === 'string') {\n return Component;\n }\n if (typeof Component === 'function') {\n return getFunctionComponentName(Component, 'Component');\n }\n\n // TypeScript can't have components as objects but they exist in the form of `memo` or `Suspense`\n if (typeof Component === 'object') {\n switch (Component.$$typeof) {\n case ForwardRef:\n return getWrappedName(Component, Component.render, 'ForwardRef');\n case Memo:\n return getWrappedName(Component, Component.type, 'memo');\n default:\n return undefined;\n }\n }\n return undefined;\n}","'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (source instanceof Uint8Array) {\n } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = new Uint8Array(zeroes + (size - it4))\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n","const basex = require('base-x')\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n",null,"'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package binary provides functions for encoding and decoding numbers in byte arrays.\n */\n\nimport { isSafeInteger } from \"@stablelib/int\";\n\n// TODO(dchest): add asserts for correct value ranges and array offsets.\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16BE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 0] << 8) | array[offset + 1]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as big-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16BE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 0] << 8) | array[offset + 1]) >>> 0;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * signed 16-bit integer and returns it.\n */\nexport function readInt16LE(array: Uint8Array, offset = 0): number {\n return (((array[offset + 1] << 8) | array[offset]) << 16) >> 16;\n}\n\n/**\n * Reads 2 bytes from array starting at offset as little-endian\n * unsigned 16-bit integer and returns it.\n */\nexport function readUint16LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 1] << 8) | array[offset]) >>> 0;\n}\n\n/**\n * Writes 2-byte big-endian representation of 16-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16BE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 8;\n out[offset + 1] = value >>> 0;\n return out;\n}\n\nexport const writeInt16BE = writeUint16BE;\n\n/**\n * Writes 2-byte little-endian representation of 16-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 2-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint16LE(value: number, out = new Uint8Array(2), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n return out;\n}\n\nexport const writeInt16LE = writeUint16LE;\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32BE(array: Uint8Array, offset = 0): number {\n return (array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32BE(array: Uint8Array, offset = 0): number {\n return ((array[offset] << 24) |\n (array[offset + 1] << 16) |\n (array[offset + 2] << 8) |\n array[offset + 3]) >>> 0;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * signed 32-bit integer and returns it.\n */\nexport function readInt32LE(array: Uint8Array, offset = 0): number {\n return (array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset];\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * unsigned 32-bit integer and returns it.\n */\nexport function readUint32LE(array: Uint8Array, offset = 0): number {\n return ((array[offset + 3] << 24) |\n (array[offset + 2] << 16) |\n (array[offset + 1] << 8) |\n array[offset]) >>> 0;\n}\n\n/**\n * Writes 4-byte big-endian representation of 32-bit unsigned\n * value to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 24;\n out[offset + 1] = value >>> 16;\n out[offset + 2] = value >>> 8;\n out[offset + 3] = value >>> 0;\n return out;\n}\n\nexport const writeInt32BE = writeUint32BE;\n\n/**\n * Writes 4-byte little-endian representation of 32-bit unsigned\n * value to array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n out[offset + 0] = value >>> 0;\n out[offset + 1] = value >>> 8;\n out[offset + 2] = value >>> 16;\n out[offset + 3] = value >>> 24;\n return out;\n}\n\n\nexport const writeInt32LE = writeUint32LE;\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64BE(array: Uint8Array, offset = 0): number {\n const hi = readInt32BE(array, offset);\n const lo = readInt32BE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64BE(array: Uint8Array, offset = 0): number {\n const hi = readUint32BE(array, offset);\n const lo = readUint32BE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * signed 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports exact\n * numbers in range -9007199254740991 to 9007199254740991.\n * If the number stored in the byte array is outside this range,\n * the result is not exact.\n */\nexport function readInt64LE(array: Uint8Array, offset = 0): number {\n const lo = readInt32LE(array, offset);\n const hi = readInt32LE(array, offset + 4);\n return hi * 0x100000000 + lo - ((lo>>31) * 0x100000000);\n}\n\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * unsigned 64-bit integer and returns it.\n *\n * IMPORTANT: due to JavaScript limitation, supports values up to 2^53-1.\n */\nexport function readUint64LE(array: Uint8Array, offset = 0): number {\n const lo = readUint32LE(array, offset);\n const hi = readUint32LE(array, offset + 4);\n return hi * 0x100000000 + lo;\n}\n\n/**\n * Writes 8-byte big-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32BE(value / 0x100000000 >>> 0, out, offset);\n writeUint32BE(value >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64BE = writeUint64BE;\n\n/**\n * Writes 8-byte little-endian representation of 64-bit unsigned\n * value to byte array starting at offset.\n *\n * Due to JavaScript limitation, supports values up to 2^53-1.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeUint64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n writeUint32LE(value >>> 0, out, offset);\n writeUint32LE(value / 0x100000000 >>> 0, out, offset + 4);\n return out;\n}\n\nexport const writeInt64LE = writeUint64LE;\n\n/**\n * Reads bytes from array starting at offset as big-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintBE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintBE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintBE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Reads bytes from array starting at offset as little-endian\n * unsigned bitLen-bit integer and returns it.\n *\n * Supports bit lengths divisible by 8, up to 48.\n */\nexport function readUintLE(bitLength: number, array: Uint8Array, offset = 0): number {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"readUintLE supports only bitLengths divisible by 8\");\n }\n if (bitLength / 8 > array.length - offset) {\n throw new Error(\"readUintLE: array is too short for the given bitLength\");\n }\n let result = 0;\n let mul = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n result += array[i] * mul;\n mul *= 256;\n }\n return result;\n}\n\n/**\n * Writes a big-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintBE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintBE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintBE value must be an integer\");\n }\n let div = 1;\n for (let i = bitLength / 8 + offset - 1; i >= offset; i--) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Writes a little-endian representation of bitLen-bit unsigned\n * value to array starting at offset.\n *\n * Supports bit lengths divisible by 8, up to 48.\n *\n * If byte array is not given, creates a new one.\n *\n * Returns the output byte array.\n */\nexport function writeUintLE(bitLength: number, value: number,\n out = new Uint8Array(bitLength / 8), offset = 0): Uint8Array {\n // TODO(dchest): implement support for bitLengths non-divisible by 8\n if (bitLength % 8 !== 0) {\n throw new Error(\"writeUintLE supports only bitLengths divisible by 8\");\n }\n if (!isSafeInteger(value)) {\n throw new Error(\"writeUintLE value must be an integer\");\n }\n let div = 1;\n for (let i = offset; i < offset + bitLength / 8; i++) {\n out[i] = (value / div) & 0xff;\n div *= 256;\n }\n return out;\n}\n\n/**\n * Reads 4 bytes from array starting at offset as big-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset);\n}\n\n/**\n * Reads 4 bytes from array starting at offset as little-endian\n * 32-bit floating-point number and returns it.\n */\nexport function readFloat32LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat32(offset, true);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as big-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64BE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset);\n}\n\n/**\n * Reads 8 bytes from array starting at offset as little-endian\n * 64-bit floating-point number (\"double\") and returns it.\n */\nexport function readFloat64LE(array: Uint8Array, offset = 0): number {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n return view.getFloat64(offset, true);\n}\n\n/**\n * Writes 4-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32BE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value);\n return out;\n}\n\n/**\n * Writes 4-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 4-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat32LE(value: number, out = new Uint8Array(4), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat32(offset, value, true);\n return out;\n}\n\n/**\n * Writes 8-byte big-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64BE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value);\n return out;\n}\n\n/**\n * Writes 8-byte little-endian floating-point representation of value\n * to byte array starting at offset.\n *\n * If byte array is not given, creates a new 8-byte one.\n *\n * Returns the output byte array.\n */\nexport function writeFloat64LE(value: number, out = new Uint8Array(8), offset = 0): Uint8Array {\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setFloat64(offset, value, true);\n return out;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha implements ChaCha stream cipher.\n */\n\nimport { writeUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\n// Number of ChaCha rounds (ChaCha20).\nconst ROUNDS = 20;\n\n// Applies the ChaCha core function to 16-byte input,\n// 32-byte key key, and puts the result into 64-byte array out.\nfunction core(out: Uint8Array, input: Uint8Array, key: Uint8Array): void {\n let j0 = 0x61707865; // \"expa\" -- ChaCha's \"sigma\" constant\n let j1 = 0x3320646E; // \"nd 3\" for 32-byte keys\n let j2 = 0x79622D32; // \"2-by\"\n let j3 = 0x6B206574; // \"te k\"\n let j4 = (key[3] << 24) | (key[2] << 16) | (key[1] << 8) | key[0];\n let j5 = (key[7] << 24) | (key[6] << 16) | (key[5] << 8) | key[4];\n let j6 = (key[11] << 24) | (key[10] << 16) | (key[9] << 8) | key[8];\n let j7 = (key[15] << 24) | (key[14] << 16) | (key[13] << 8) | key[12];\n let j8 = (key[19] << 24) | (key[18] << 16) | (key[17] << 8) | key[16];\n let j9 = (key[23] << 24) | (key[22] << 16) | (key[21] << 8) | key[20];\n let j10 = (key[27] << 24) | (key[26] << 16) | (key[25] << 8) | key[24];\n let j11 = (key[31] << 24) | (key[30] << 16) | (key[29] << 8) | key[28];\n let j12 = (input[3] << 24) | (input[2] << 16) | (input[1] << 8) | input[0];\n let j13 = (input[7] << 24) | (input[6] << 16) | (input[5] << 8) | input[4];\n let j14 = (input[11] << 24) | (input[10] << 16) | (input[9] << 8) | input[8];\n let j15 = (input[15] << 24) | (input[14] << 16) | (input[13] << 8) | input[12];\n\n let x0 = j0;\n let x1 = j1;\n let x2 = j2;\n let x3 = j3;\n let x4 = j4;\n let x5 = j5;\n let x6 = j6;\n let x7 = j7;\n let x8 = j8;\n let x9 = j9;\n let x10 = j10;\n let x11 = j11;\n let x12 = j12;\n let x13 = j13;\n let x14 = j14;\n let x15 = j15;\n\n for (let i = 0; i < ROUNDS; i += 2) {\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 16) | x12 << 16;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 12) | x4 << 12;\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 16) | x13 << 16;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 12) | x5 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 16) | x14 << 16;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 12) | x6 << 12;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 16) | x15 << 16;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 12) | x7 << 12;\n\n x2 = x2 + x6 | 0; x14 ^= x2; x14 = x14 >>> (32 - 8) | x14 << 8;\n x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> (32 - 7) | x6 << 7;\n x3 = x3 + x7 | 0; x15 ^= x3; x15 = x15 >>> (32 - 8) | x15 << 8;\n x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> (32 - 7) | x7 << 7;\n\n x1 = x1 + x5 | 0; x13 ^= x1; x13 = x13 >>> (32 - 8) | x13 << 8;\n x9 = x9 + x13 | 0; x5 ^= x9; x5 = x5 >>> (32 - 7) | x5 << 7;\n x0 = x0 + x4 | 0; x12 ^= x0; x12 = x12 >>> (32 - 8) | x12 << 8;\n x8 = x8 + x12 | 0; x4 ^= x8; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 16) | x15 << 16;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 12) | x5 << 12;\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 16) | x12 << 16;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 12) | x6 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 16) | x13 << 16;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 12) | x7 << 12;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 16) | x14 << 16;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 12) | x4 << 12;\n\n x2 = x2 + x7 | 0; x13 ^= x2; x13 = x13 >>> (32 - 8) | x13 << 8;\n x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> (32 - 7) | x7 << 7;\n x3 = x3 + x4 | 0; x14 ^= x3; x14 = x14 >>> (32 - 8) | x14 << 8;\n x9 = x9 + x14 | 0; x4 ^= x9; x4 = x4 >>> (32 - 7) | x4 << 7;\n\n x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> (32 - 8) | x12 << 8;\n x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> (32 - 7) | x6 << 7;\n x0 = x0 + x5 | 0; x15 ^= x0; x15 = x15 >>> (32 - 8) | x15 << 8;\n x10 = x10 + x15 | 0; x5 ^= x10; x5 = x5 >>> (32 - 7) | x5 << 7;\n }\n writeUint32LE(x0 + j0 | 0, out, 0);\n writeUint32LE(x1 + j1 | 0, out, 4);\n writeUint32LE(x2 + j2 | 0, out, 8);\n writeUint32LE(x3 + j3 | 0, out, 12);\n writeUint32LE(x4 + j4 | 0, out, 16);\n writeUint32LE(x5 + j5 | 0, out, 20);\n writeUint32LE(x6 + j6 | 0, out, 24);\n writeUint32LE(x7 + j7 | 0, out, 28);\n writeUint32LE(x8 + j8 | 0, out, 32);\n writeUint32LE(x9 + j9 | 0, out, 36);\n writeUint32LE(x10 + j10 | 0, out, 40);\n writeUint32LE(x11 + j11 | 0, out, 44);\n writeUint32LE(x12 + j12 | 0, out, 48);\n writeUint32LE(x13 + j13 | 0, out, 52);\n writeUint32LE(x14 + j14 | 0, out, 56);\n writeUint32LE(x15 + j15 | 0, out, 60);\n}\n\n/**\n * Encrypt src with ChaCha20 stream generated for the given 32-byte key and\n * 8-byte (as in original implementation) or 12-byte (as in RFC7539) nonce and\n * write the result into dst and return it.\n *\n * dst and src may be the same, but otherwise must not overlap.\n *\n * If nonce is 12 bytes, users should not encrypt more than 256 GiB with the\n * same key and nonce, otherwise the stream will repeat. The function will\n * throw error if counter overflows to prevent this.\n *\n * If nonce is 8 bytes, the output is practically unlimited (2^70 bytes, which\n * is more than a million petabytes). However, it is not recommended to\n * generate 8-byte nonces randomly, as the chance of collision is high.\n *\n * Never use the same key and nonce to encrypt more than one message.\n *\n * If nonceInplaceCounterLength is not 0, the nonce is assumed to be a 16-byte\n * array with stream counter in first nonceInplaceCounterLength bytes and nonce\n * in the last remaining bytes. The counter will be incremented inplace for\n * each ChaCha block. This is useful if you need to encrypt one stream of data\n * in chunks.\n */\nexport function streamXOR(key: Uint8Array, nonce: Uint8Array,\n src: Uint8Array, dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n // We only support 256-bit keys.\n if (key.length !== 32) {\n throw new Error(\"ChaCha: key size must be 32 bytes\");\n }\n\n if (dst.length < src.length) {\n throw new Error(\"ChaCha: destination is shorter than source\");\n }\n\n let nc: Uint8Array;\n let counterLength: number;\n\n if (nonceInplaceCounterLength === 0) {\n if (nonce.length !== 8 && nonce.length !== 12) {\n throw new Error(\"ChaCha nonce must be 8 or 12 bytes\");\n }\n nc = new Uint8Array(16);\n // First counterLength bytes of nc are counter, starting with zero.\n counterLength = nc.length - nonce.length;\n // Last bytes of nc after counterLength are nonce, set them.\n nc.set(nonce, counterLength);\n } else {\n if (nonce.length !== 16) {\n throw new Error(\"ChaCha nonce with counter must be 16 bytes\");\n }\n // This will update passed nonce with counter inplace.\n nc = nonce;\n counterLength = nonceInplaceCounterLength;\n }\n\n // Allocate temporary space for ChaCha block.\n const block = new Uint8Array(64);\n\n for (let i = 0; i < src.length; i += 64) {\n // Generate a block.\n core(block, nc, key);\n\n // XOR block bytes with src into dst.\n for (let j = i; j < i + 64 && j < src.length; j++) {\n dst[j] = src[j] ^ block[j - i];\n }\n\n // Increment counter.\n incrementCounter(nc, 0, counterLength);\n }\n\n // Cleanup temporary space.\n wipe(block);\n\n if (nonceInplaceCounterLength === 0) {\n // Cleanup counter.\n wipe(nc);\n }\n\n return dst;\n}\n\n/**\n * Generate ChaCha20 stream for the given 32-byte key and 8-byte or 12-byte\n * nonce and write it into dst and return it.\n *\n * Never use the same key and nonce to generate more than one stream.\n *\n * If nonceInplaceCounterLength is not 0, it behaves the same with respect to\n * the nonce as described in the streamXOR documentation.\n *\n * stream is like streamXOR with all-zero src.\n */\nexport function stream(key: Uint8Array, nonce: Uint8Array,\n dst: Uint8Array, nonceInplaceCounterLength = 0): Uint8Array {\n wipe(dst);\n return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength);\n}\n\nfunction incrementCounter(counter: Uint8Array, pos: number, len: number) {\n let carry = 1;\n while (len--) {\n carry = carry + (counter[pos] & 0xff) | 0;\n counter[pos] = carry & 0xff;\n carry >>>= 8;\n pos++;\n }\n if (carry > 0) {\n throw new Error(\"ChaCha: counter overflow\");\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package chacha20poly1305 implements ChaCha20-Poly1305 AEAD.\n */\n\nimport { AEAD } from \"@stablelib/aead\";\nimport { streamXOR, stream } from \"@stablelib/chacha\";\nimport { Poly1305 } from \"@stablelib/poly1305\";\nimport { wipe } from \"@stablelib/wipe\";\nimport { writeUint64LE } from \"@stablelib/binary\";\nimport { equal } from \"@stablelib/constant-time\";\n\nexport const KEY_LENGTH = 32;\nexport const NONCE_LENGTH = 12;\nexport const TAG_LENGTH = 16;\n\nconst ZEROS = new Uint8Array(16);\n\n/**\n * ChaCha20-Poly1305 Authenticated Encryption with Associated Data.\n *\n * Defined in RFC7539.\n */\nexport class ChaCha20Poly1305 implements AEAD {\n readonly nonceLength = NONCE_LENGTH;\n readonly tagLength = TAG_LENGTH;\n\n private _key: Uint8Array;\n\n /**\n * Creates a new instance with the given 32-byte key.\n */\n constructor(key: Uint8Array) {\n if (key.length !== KEY_LENGTH) {\n throw new Error(\"ChaCha20Poly1305 needs 32-byte key\");\n }\n // Copy key.\n this._key = new Uint8Array(key);\n }\n\n /**\n * Encrypts and authenticates plaintext, authenticates associated data,\n * and returns sealed ciphertext, which includes authentication tag.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If dst is given (it must be the size of plaintext + the size of tag\n * length) the result will be put into it. Dst and plaintext must not\n * overlap.\n */\n seal(nonce: Uint8Array, plaintext: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n // We pass full counter, which has 12-byte nonce and 4-byte block counter,\n // and it will get incremented after generating the block, which is\n // exactly what we need: we only use the first 32 bytes of 64-byte\n // ChaCha block and discard the next 32 bytes.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Allocate space for sealed ciphertext.\n const resultLength = plaintext.length + this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Encrypt plaintext.\n streamXOR(this._key, counter, plaintext, result, 4);\n\n // Authenticate.\n // XXX: can \"simplify\" here: pass full result (which is already padded\n // due to zeroes prepared for tag), and ciphertext length instead of\n // subarray of result.\n this._authenticate(result.subarray(result.length - this.tagLength, result.length),\n authKey, result.subarray(0, result.length - this.tagLength), associatedData);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n /**\n * Authenticates sealed ciphertext (which includes authentication tag) and\n * associated data, decrypts ciphertext and returns decrypted plaintext.\n *\n * RFC7539 specifies 12 bytes for nonce. It may be this 12-byte nonce\n * (\"IV\"), or full 16-byte counter (called \"32-bit fixed-common part\")\n * and nonce.\n *\n * If authentication fails, it returns null.\n *\n * If dst is given (it must be of ciphertext length minus tag length),\n * the result will be put into it. Dst and plaintext must not overlap.\n */\n open(nonce: Uint8Array, sealed: Uint8Array, associatedData?: Uint8Array,\n dst?: Uint8Array): Uint8Array | null {\n if (nonce.length > 16) {\n throw new Error(\"ChaCha20Poly1305: incorrect nonce length\");\n }\n\n // Sealed ciphertext should at least contain tag.\n if (sealed.length < this.tagLength) {\n // TODO(dchest): should we throw here instead?\n return null;\n }\n\n // Allocate space for counter, and set nonce as last bytes of it.\n const counter = new Uint8Array(16);\n counter.set(nonce, counter.length - nonce.length);\n\n // Generate authentication key by taking first 32-bytes of stream.\n const authKey = new Uint8Array(32);\n stream(this._key, counter, authKey, 4);\n\n // Authenticate.\n // XXX: can simplify and avoid allocation: since authenticate()\n // already allocates tag (from Poly1305.digest(), it can return)\n // it instead of copying to calculatedTag. But then in seal()\n // we'll need to copy it.\n const calculatedTag = new Uint8Array(this.tagLength);\n this._authenticate(calculatedTag, authKey,\n sealed.subarray(0, sealed.length - this.tagLength), associatedData);\n\n // Constant-time compare tags and return null if they differ.\n if (!equal(calculatedTag,\n sealed.subarray(sealed.length - this.tagLength, sealed.length))) {\n return null;\n }\n\n // Allocate space for decrypted plaintext.\n const resultLength = sealed.length - this.tagLength;\n let result;\n if (dst) {\n if (dst.length !== resultLength) {\n throw new Error(\"ChaCha20Poly1305: incorrect destination length\");\n }\n result = dst;\n } else {\n result = new Uint8Array(resultLength);\n }\n\n // Decrypt.\n streamXOR(this._key, counter,\n sealed.subarray(0, sealed.length - this.tagLength), result, 4);\n\n // Cleanup.\n wipe(counter);\n\n return result;\n }\n\n clean(): this {\n wipe(this._key);\n return this;\n }\n\n private _authenticate(tagOut: Uint8Array, authKey: Uint8Array,\n ciphertext: Uint8Array, associatedData?: Uint8Array) {\n\n // Initialize Poly1305 with authKey.\n const h = new Poly1305(authKey);\n\n // Authenticate padded associated data.\n if (associatedData) {\n h.update(associatedData);\n if (associatedData.length % 16 > 0) {\n h.update(ZEROS.subarray(associatedData.length % 16));\n }\n }\n\n // Authenticate padded ciphertext.\n h.update(ciphertext);\n if (ciphertext.length % 16 > 0) {\n h.update(ZEROS.subarray(ciphertext.length % 16));\n }\n\n // Authenticate length of associated data.\n // XXX: can avoid allocation here?\n const length = new Uint8Array(8);\n if (associatedData) {\n writeUint64LE(associatedData.length, length);\n }\n h.update(length);\n\n // Authenticate length of ciphertext.\n writeUint64LE(ciphertext.length, length);\n h.update(length);\n\n // Get tag and copy it into tagOut.\n const tag = h.digest();\n for (let i = 0; i < tag.length; i++) {\n tagOut[i] = tag[i];\n }\n\n // Cleanup.\n h.clean();\n wipe(tag);\n wipe(length);\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package constant-time provides functions for performing algorithmically constant-time operations.\n */\n\n/**\n * NOTE! Due to the inability to guarantee real constant time evaluation of\n * anything in JavaScript VM, this is module is the best effort.\n */\n\n/**\n * Returns resultIfOne if subject is 1, or resultIfZero if subject is 0.\n *\n * Supports only 32-bit integers, so resultIfOne or resultIfZero are not\n * integers, they'll be converted to them with bitwise operations.\n */\nexport function select(subject: number, resultIfOne: number, resultIfZero: number): number {\n return (~(subject - 1) & resultIfOne) | ((subject - 1) & resultIfZero);\n}\n\n/**\n * Returns 1 if a <= b, or 0 if not.\n * Arguments must be positive 32-bit integers less than or equal to 2^31 - 1.\n */\nexport function lessOrEqual(a: number, b: number): number {\n return (((a | 0) - (b | 0) - 1) >>> 31) & 1;\n}\n\n/**\n * Returns 1 if a and b are of equal length and their contents\n * are equal, or 0 otherwise.\n *\n * Note that unlike in equal(), zero-length inputs are considered\n * the same, so this function will return 1.\n */\nexport function compare(a: Uint8Array, b: Uint8Array): number {\n if (a.length !== b.length) {\n return 0;\n }\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return (1 & ((result - 1) >>> 8));\n}\n\n/**\n * Returns true if a and b are of equal non-zero length,\n * and their contents are equal, or false otherwise.\n *\n * Note that unlike in compare() zero-length inputs are considered\n * _not_ equal, so this function will return false.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length === 0 || b.length === 0) {\n return false;\n }\n return compare(a, b) !== 0;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package ed25519 implements Ed25519 public-key signature algorithm.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { hash, SHA512 } from \"@stablelib/sha512\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const SIGNATURE_LENGTH = 64;\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\nexport const SEED_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../kex/x25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which was ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst gf0 = gf();\n\nconst gf1 = gf([1]);\n\nconst D = gf([\n 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,\n 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203\n]);\n\nconst D2 = gf([\n 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,\n 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406\n]);\n\nconst X = gf([\n 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,\n 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169\n]);\n\nconst Y = gf([\n 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,\n 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666\n]);\n\nconst I = gf([\n 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,\n 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83\n]);\n\nfunction set25519(r: GF, a: GF) {\n for (let i = 0; i < 16; i++) {\n r[i] = a[i] | 0;\n }\n}\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction verify32(x: Uint8Array, y: Uint8Array) {\n let d = 0;\n for (let i = 0; i < 32; i++) {\n d |= x[i] ^ y[i];\n }\n return (1 & ((d - 1) >>> 8)) - 1;\n}\n\n\nfunction neq25519(a: GF, b: GF) {\n const c = new Uint8Array(32);\n const d = new Uint8Array(32);\n pack25519(c, a);\n pack25519(d, b);\n return verify32(c, d);\n}\n\nfunction par25519(a: GF) {\n const d = new Uint8Array(32);\n pack25519(d, a);\n return d[0] & 1;\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, i: GF) {\n const c = gf();\n let a: number;\n for (a = 0; a < 16; a++) {\n c[a] = i[a];\n }\n for (a = 253; a >= 0; a--) {\n square(c, c);\n if (a !== 2 && a !== 4) {\n mul(c, c, i);\n }\n }\n for (a = 0; a < 16; a++) {\n o[a] = c[a];\n }\n}\n\nfunction pow2523(o: GF, i: GF) {\n const c = gf();\n let a: number;\n for (a = 0; a < 16; a++) {\n c[a] = i[a];\n }\n for (a = 250; a >= 0; a--) {\n square(c, c);\n if (a !== 1) {\n mul(c, c, i);\n }\n }\n for (a = 0; a < 16; a++) {\n o[a] = c[a];\n }\n}\n\n\nfunction edadd(p: GF[], q: GF[]) {\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf(),\n g = gf(), h = gf(), t = gf();\n\n sub(a, p[1], p[0]);\n sub(t, q[1], q[0]);\n mul(a, a, t);\n add(b, p[0], p[1]);\n add(t, q[0], q[1]);\n mul(b, b, t);\n mul(c, p[3], q[3]);\n mul(c, c, D2);\n mul(d, p[2], q[2]);\n add(d, d, d);\n sub(e, b, a);\n sub(f, d, c);\n add(g, d, c);\n add(h, b, a);\n\n mul(p[0], e, f);\n mul(p[1], h, g);\n mul(p[2], g, f);\n mul(p[3], e, h);\n}\n\nfunction cswap(p: GF[], q: GF[], b: number) {\n for (let i = 0; i < 4; i++) {\n sel25519(p[i], q[i], b);\n }\n}\n\nfunction pack(r: Uint8Array, p: GF[]) {\n const tx = gf(), ty = gf(), zi = gf();\n inv25519(zi, p[2]);\n mul(tx, p[0], zi);\n mul(ty, p[1], zi);\n pack25519(r, ty);\n r[31] ^= par25519(tx) << 7;\n}\n\nfunction scalarmult(p: GF[], q: GF[], s: Uint8Array) {\n set25519(p[0], gf0);\n set25519(p[1], gf1);\n set25519(p[2], gf1);\n set25519(p[3], gf0);\n for (let i = 255; i >= 0; --i) {\n const b = (s[(i / 8) | 0] >> (i & 7)) & 1;\n cswap(p, q, b);\n edadd(q, p);\n edadd(p, p);\n cswap(p, q, b);\n }\n}\n\nfunction scalarbase(p: GF[], s: Uint8Array) {\n const q = [gf(), gf(), gf(), gf()];\n set25519(q[0], X);\n set25519(q[1], Y);\n set25519(q[2], gf1);\n mul(q[3], X, Y);\n scalarmult(p, q, s);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\n// Generates key pair from secret 32-byte seed.\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SEED_LENGTH) {\n throw new Error(`ed25519: seed must be ${SEED_LENGTH} bytes`);\n }\n\n const d = hash(seed);\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n const publicKey = new Uint8Array(32);\n const p = [gf(), gf(), gf(), gf()];\n scalarbase(p, d);\n pack(publicKey, p);\n\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\nexport function extractPublicKeyFromSecretKey(secretKey: Uint8Array): Uint8Array {\n if (secretKey.length !== SECRET_KEY_LENGTH) {\n throw new Error(`ed25519: secret key must be ${SECRET_KEY_LENGTH} bytes`);\n }\n return new Uint8Array(secretKey.subarray(32));\n}\n\nconst L = new Float64Array([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2,\n 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10\n]);\n\nfunction modL(r: Uint8Array, x: Float64Array) {\n let carry: number;\n let i: number;\n let j: number;\n let k: number;\n for (i = 63; i >= 32; --i) {\n carry = 0;\n for (j = i - 32, k = i - 12; j < k; ++j) {\n x[j] += carry - 16 * x[i] * L[j - (i - 32)];\n carry = Math.floor((x[j] + 128) / 256);\n x[j] -= carry * 256;\n }\n x[j] += carry;\n x[i] = 0;\n }\n carry = 0;\n for (j = 0; j < 32; j++) {\n x[j] += carry - (x[31] >> 4) * L[j];\n carry = x[j] >> 8;\n x[j] &= 255;\n }\n for (j = 0; j < 32; j++) {\n x[j] -= carry * L[j];\n }\n for (i = 0; i < 32; i++) {\n x[i + 1] += x[i] >> 8;\n r[i] = x[i] & 255;\n }\n}\n\nfunction reduce(r: Uint8Array) {\n const x = new Float64Array(64);\n for (let i = 0; i < 64; i++) {\n x[i] = r[i];\n }\n for (let i = 0; i < 64; i++) {\n r[i] = 0;\n }\n modL(r, x);\n}\n\n// Returns 64-byte signature of the message under the 64-byte secret key.\nexport function sign(secretKey: Uint8Array, message: Uint8Array): Uint8Array {\n const x = new Float64Array(64);\n const p = [gf(), gf(), gf(), gf()];\n\n const d = hash(secretKey.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n\n const signature = new Uint8Array(64);\n signature.set(d.subarray(32), 32);\n\n const hs = new SHA512();\n hs.update(signature.subarray(32));\n hs.update(message);\n const r = hs.digest();\n hs.clean();\n reduce(r);\n scalarbase(p, r);\n pack(signature, p);\n\n hs.reset();\n hs.update(signature.subarray(0, 32));\n hs.update(secretKey.subarray(32));\n hs.update(message);\n const h = hs.digest();\n reduce(h);\n\n for (let i = 0; i < 32; i++) {\n x[i] = r[i];\n }\n for (let i = 0; i < 32; i++) {\n for (let j = 0; j < 32; j++) {\n x[i + j] += h[i] * d[j];\n }\n }\n modL(signature.subarray(32), x);\n\n return signature;\n}\n\nfunction unpackneg(r: GF[], p: Uint8Array) {\n const t = gf(), chk = gf(), num = gf(),\n den = gf(), den2 = gf(), den4 = gf(),\n den6 = gf();\n\n set25519(r[2], gf1);\n unpack25519(r[1], p);\n square(num, r[1]);\n mul(den, num, D);\n sub(num, num, r[2]);\n add(den, r[2], den);\n\n square(den2, den);\n square(den4, den2);\n mul(den6, den4, den2);\n mul(t, den6, num);\n mul(t, t, den);\n\n pow2523(t, t);\n mul(t, t, num);\n mul(t, t, den);\n mul(t, t, den);\n mul(r[0], t, den);\n\n square(chk, r[0]);\n mul(chk, chk, den);\n if (neq25519(chk, num)) {\n mul(r[0], r[0], I);\n }\n\n square(chk, r[0]);\n mul(chk, chk, den);\n if (neq25519(chk, num)) {\n return -1;\n }\n\n if (par25519(r[0]) === (p[31] >> 7)) {\n sub(r[0], gf0, r[0]);\n }\n\n mul(r[3], r[0], r[1]);\n return 0;\n}\n\nexport function verify(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean {\n const t = new Uint8Array(32);\n const p = [gf(), gf(), gf(), gf()];\n const q = [gf(), gf(), gf(), gf()];\n\n if (signature.length !== SIGNATURE_LENGTH) {\n throw new Error(`ed25519: signature must be ${SIGNATURE_LENGTH} bytes`);\n }\n\n if (unpackneg(q, publicKey)) {\n return false;\n }\n\n const hs = new SHA512();\n hs.update(signature.subarray(0, 32));\n hs.update(publicKey);\n hs.update(message);\n const h = hs.digest();\n reduce(h);\n scalarmult(p, q, h);\n\n scalarbase(q, signature.subarray(32));\n edadd(p, q);\n pack(t, p);\n\n if (verify32(signature, t)) {\n return false;\n }\n return true;\n}\n\n/**\n * Convert Ed25519 public key to X25519 public key.\n *\n * Throws if given an invalid public key.\n */\nexport function convertPublicKeyToX25519(publicKey: Uint8Array): Uint8Array {\n let q = [gf(), gf(), gf(), gf()];\n\n if (unpackneg(q, publicKey)) {\n throw new Error(\"Ed25519: invalid public key\");\n }\n\n // Formula: montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p\n let a = gf();\n let b = gf();\n let y = q[1];\n add(a, gf1, y);\n sub(b, gf1, y);\n inv25519(b, b);\n mul(a, a, b);\n\n let z = new Uint8Array(32);\n pack25519(z, a);\n return z;\n}\n\n/**\n * Convert Ed25519 secret (private) key to X25519 secret key.\n */\nexport function convertSecretKeyToX25519(secretKey: Uint8Array): Uint8Array {\n const d = hash(secretKey.subarray(0, 32));\n d[0] &= 248;\n d[31] &= 127;\n d[31] |= 64;\n const o = new Uint8Array(d.subarray(0, 32));\n wipe(d);\n return o;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hash provides interface for hash functions.\n */\n\n/**\n * Hash interface describes properties of\n * cryptographic hash functions.\n */\nexport interface Hash {\n readonly digestLength: number;\n readonly blockSize: number;\n update(data: Uint8Array): this;\n reset(): this;\n finish(out: Uint8Array): this;\n digest(): Uint8Array;\n clean(): void;\n}\n\nexport interface SerializableHash extends Hash {\n saveState(): any;\n restoreState(savedState: any): this;\n cleanSavedState(savedState: any): void;\n}\n\nexport function isSerializableHash(h: Hash): h is SerializableHash {\n return (\n typeof (h as SerializableHash).saveState !== \"undefined\" &&\n typeof (h as SerializableHash).restoreState !== \"undefined\" &&\n typeof (h as SerializableHash).cleanSavedState !== \"undefined\"\n );\n}\n\n// TODO(dchest): figure out the standardized interface for XOF such as\n// SHAKE and BLAKE2X.\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hkdf implements HKDF key derivation function.\n */\n\nimport { Hash } from \"@stablelib/hash\";\nimport { HMAC, hmac } from \"@stablelib/hmac\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC-based Extract-and-Expand Key Derivation Function.\n *\n * Implements HKDF from RFC5869.\n *\n * Expands the given master key with salt and info into\n * a limited stream of key material.\n */\nexport class HKDF {\n private _hmac: HMAC;\n private _buffer: Uint8Array;\n private _bufpos: number;\n private _counter = new Uint8Array(1); // starts with zero\n private _hash: new () => Hash;\n private _info?: Uint8Array;\n\n /**\n * Create a new HKDF instance for the given hash function\n * with the master key, optional salt, and info.\n *\n * - Master key is a high-entropy secret key (not a password).\n * - Salt is a non-secret random value.\n * - Info is application- and/or context-specific information.\n */\n constructor(hash: new () => Hash,\n key: Uint8Array,\n salt = new Uint8Array(0),\n info?: Uint8Array) {\n\n this._hash = hash;\n this._info = info;\n\n // HKDF-Extract uses salt as HMAC key, and key as data.\n const okm = hmac(this._hash, salt, key);\n\n // Initialize HMAC for expanding with extracted key.\n this._hmac = new HMAC(hash, okm);\n\n // Allocate buffer.\n this._buffer = new Uint8Array(this._hmac.digestLength);\n this._bufpos = this._buffer.length;\n }\n\n // Fill buffer with new block of HKDF-Extract output.\n private _fillBuffer(): void {\n // Increment counter.\n this._counter[0]++;\n\n const ctr = this._counter[0];\n\n // Check if counter overflowed.\n if (ctr === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n\n // Prepare HMAC instance for new data with old key.\n this._hmac.reset();\n\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (ctr > 1) {\n this._hmac.update(this._buffer);\n }\n\n // Hash in info if it exists.\n if (this._info) {\n this._hmac.update(this._info);\n }\n\n // Hash in the counter.\n this._hmac.update(this._counter);\n\n // Output result to buffer and clean HMAC instance.\n this._hmac.finish(this._buffer);\n\n // Reset buffer position.\n this._bufpos = 0;\n }\n\n /**\n * Expand returns next key material of the given length.\n *\n * It throws if expansion limit is reached (which is\n * 254 digests of the underlying HMAC function).\n */\n expand(length: number): Uint8Array {\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i++) {\n if (this._bufpos === this._buffer.length) {\n this._fillBuffer();\n }\n out[i] = this._buffer[this._bufpos++];\n }\n return out;\n }\n\n clean(): void {\n this._hmac.clean();\n wipe(this._buffer);\n wipe(this._counter);\n this._bufpos = 0;\n }\n}\n\n// TODO(dchest): maybe implement deriveKey?\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package hmac implements HMAC algorithm.\n */\n\nimport { Hash, SerializableHash, isSerializableHash } from \"@stablelib/hash\";\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\n/**\n * HMAC implements hash-based message authentication algorithm.\n */\nexport class HMAC implements SerializableHash {\n readonly blockSize: number;\n readonly digestLength: number;\n\n private _inner: Hash; // inner hash\n private _outer: Hash; // outer hash\n\n private _finished = false; // true if HMAC was finalized\n\n // Copies of hash states after keying.\n // Need for quick reset without hashing the key again.\n private _innerKeyedState: any | undefined;\n private _outerKeyedState: any | undefined;\n\n /**\n * Constructs a new HMAC with the given Hash and secret key.\n */\n constructor(hash: new () => Hash | SerializableHash, key: Uint8Array) {\n // Initialize inner and outer hashes.\n this._inner = new hash();\n this._outer = new hash();\n\n // Set block and digest sizes for this HMAC\n // instance to values from the hash.\n this.blockSize = this._outer.blockSize;\n this.digestLength = this._outer.digestLength;\n\n // Pad temporary stores a key (or its hash) padded with zeroes.\n const pad = new Uint8Array(this.blockSize);\n\n if (key.length > this.blockSize) {\n // If key is bigger than hash block size, it must be\n // hashed and this hash is used as a key instead.\n this._inner.update(key).finish(pad).clean();\n } else {\n // Otherwise, copy the key into pad.\n pad.set(key);\n }\n\n // Now two different keys are derived from padded key\n // by xoring a different byte value to each.\n\n // To make inner hash key, xor byte 0x36 into pad.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n // Update inner hash with the result.\n this._inner.update(pad);\n\n // To make outer hash key, xor byte 0x5c into pad.\n // But since we already xored 0x36 there, we must\n // first undo this by xoring it again.\n for (let i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n // Update outer hash with the result.\n this._outer.update(pad);\n\n // Save states of both hashes, so that we can quickly restore\n // them later in reset() without the need to remember the actual\n // key and perform this initialization again.\n if (isSerializableHash(this._inner) && isSerializableHash(this._outer)) {\n this._innerKeyedState = this._inner.saveState();\n this._outerKeyedState = this._outer.saveState();\n }\n\n // Clean pad.\n wipe(pad);\n }\n\n /**\n * Returns HMAC state to the state initialized with key\n * to make it possible to run HMAC over the other data with the same\n * key without creating a new instance.\n */\n reset(): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't reset() because hash doesn't implement restoreState()\");\n }\n // Restore keyed states of inner and outer hashes.\n this._inner.restoreState(this._innerKeyedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans HMAC state.\n */\n clean() {\n if (isSerializableHash(this._inner)) {\n this._inner.cleanSavedState(this._innerKeyedState);\n }\n if (isSerializableHash(this._outer)) {\n this._outer.cleanSavedState(this._outerKeyedState);\n }\n this._inner.clean();\n this._outer.clean();\n }\n\n /**\n * Updates state with provided data.\n */\n update(data: Uint8Array): this {\n this._inner.update(data);\n return this;\n }\n\n /**\n * Finalizes HMAC and puts the result in out.\n */\n finish(out: Uint8Array): this {\n if (this._finished) {\n // If HMAC was finalized, outer hash is also finalized,\n // so it produces the same digest it produced when it\n // was finalized.\n this._outer.finish(out);\n return this;\n }\n\n // Finalize inner hash and store the result temporarily.\n this._inner.finish(out);\n\n // Update outer hash with digest of inner hash and and finalize it.\n this._outer.update(out.subarray(0, this.digestLength)).finish(out);\n this._finished = true;\n\n return this;\n }\n\n /**\n * Returns the computed message authentication code.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Saves HMAC state.\n * This function is needed for PBKDF2 optimization.\n */\n saveState(): any {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't saveState() because hash doesn't implement it\");\n }\n return this._inner.saveState();\n }\n\n restoreState(savedState: any): this {\n if (!isSerializableHash(this._inner) || !isSerializableHash(this._outer)) {\n throw new Error(\"hmac: can't restoreState() because hash doesn't implement it\");\n }\n this._inner.restoreState(savedState);\n this._outer.restoreState(this._outerKeyedState);\n this._finished = false;\n return this;\n }\n\n cleanSavedState(savedState: any) {\n if (!isSerializableHash(this._inner)) {\n throw new Error(\"hmac: can't cleanSavedState() because hash doesn't implement it\");\n }\n this._inner.cleanSavedState(savedState);\n }\n}\n\n/**\n * Returns HMAC using the given hash constructor for the key over data.\n */\nexport function hmac(hash: new () => Hash, key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new HMAC(hash, key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two HMAC digests are equal.\n * Uses constant-time comparison to avoid leaking timing information.\n *\n * Example:\n *\n * const receivedDigest = ...\n * const realDigest = hmac(SHA256, key, data);\n * if (!equal(receivedDigest, realDigest)) {\n * throw new Error(\"Authentication error\");\n * }\n */\nexport const equal = constantTimeEqual;\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package int provides helper functions for integerss.\n */\n\n// Shim using 16-bit pieces.\nfunction imulShim(a: number, b: number): number {\n const ah = (a >>> 16) & 0xffff, al = a & 0xffff;\n const bh = (b >>> 16) & 0xffff, bl = b & 0xffff;\n return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);\n}\n\n/** 32-bit integer multiplication. */\n// Use system Math.imul if available, otherwise use our shim.\nexport const mul = (Math as { imul?(a: number, b: number): number }).imul || imulShim;\n\n/** 32-bit integer addition. */\nexport function add(a: number, b: number): number {\n return (a + b) | 0;\n}\n\n/** 32-bit integer subtraction. */\nexport function sub(a: number, b: number): number {\n return (a - b) | 0;\n}\n\n/** 32-bit integer left rotation */\nexport function rotl(x: number, n: number): number {\n return x << n | x >>> (32 - n);\n}\n\n/** 32-bit integer left rotation */\nexport function rotr(x: number, n: number): number {\n return x << (32 - n) | x >>> n;\n}\n\nfunction isIntegerShim(n: number): boolean {\n return typeof n === \"number\" && isFinite(n) && Math.floor(n) === n;\n}\n\n/**\n * Returns true if the argument is an integer number.\n *\n * In ES2015, Number.isInteger.\n */\nexport const isInteger = (Number as { isInteger?(n: number): boolean }).isInteger || isIntegerShim;\n\n/**\n * Math.pow(2, 53) - 1\n *\n * In ES2015 Number.MAX_SAFE_INTEGER.\n */\nexport const MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Returns true if the argument is a safe integer number\n * (-MIN_SAFE_INTEGER < number <= MAX_SAFE_INTEGER)\n *\n * In ES2015, Number.isSafeInteger.\n */\nexport const isSafeInteger = (n: number): boolean =>\n isInteger(n) && (n >= -MAX_SAFE_INTEGER && n <= MAX_SAFE_INTEGER);\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package poly1305 implements Poly1305 one-time message authentication algorithm.\n */\n\nimport { equal as constantTimeEqual } from \"@stablelib/constant-time\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 16;\n\n// Port of Andrew Moon's Poly1305-donna-16. Public domain.\n// https://github.com/floodyberry/poly1305-donna\n\n/**\n * Poly1305 computes 16-byte authenticator of message using\n * a one-time 32-byte key.\n *\n * Important: key should be used for only one message,\n * it should never repeat.\n */\nexport class Poly1305 {\n readonly digestLength = DIGEST_LENGTH;\n\n private _buffer = new Uint8Array(16);\n private _r = new Uint16Array(10);\n private _h = new Uint16Array(10);\n private _pad = new Uint16Array(8);\n private _leftover = 0;\n private _fin = 0;\n private _finished = false;\n\n constructor(key: Uint8Array) {\n let t0 = key[0] | key[1] << 8; this._r[0] = (t0) & 0x1fff;\n let t1 = key[2] | key[3] << 8; this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = key[4] | key[5] << 8; this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n let t3 = key[6] | key[7] << 8; this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = key[8] | key[9] << 8; this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this._r[5] = ((t4 >>> 1)) & 0x1ffe;\n let t5 = key[10] | key[11] << 8; this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = key[12] | key[13] << 8; this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n let t7 = key[14] | key[15] << 8; this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this._r[9] = ((t7 >>> 5)) & 0x007f;\n\n this._pad[0] = key[16] | key[17] << 8;\n this._pad[1] = key[18] | key[19] << 8;\n this._pad[2] = key[20] | key[21] << 8;\n this._pad[3] = key[22] | key[23] << 8;\n this._pad[4] = key[24] | key[25] << 8;\n this._pad[5] = key[26] | key[27] << 8;\n this._pad[6] = key[28] | key[29] << 8;\n this._pad[7] = key[30] | key[31] << 8;\n }\n\n private _blocks(m: Uint8Array, mpos: number, bytes: number) {\n let hibit = this._fin ? 0 : 1 << 11;\n\n let h0 = this._h[0],\n h1 = this._h[1],\n h2 = this._h[2],\n h3 = this._h[3],\n h4 = this._h[4],\n h5 = this._h[5],\n h6 = this._h[6],\n h7 = this._h[7],\n h8 = this._h[8],\n h9 = this._h[9];\n\n let r0 = this._r[0],\n r1 = this._r[1],\n r2 = this._r[2],\n r3 = this._r[3],\n r4 = this._r[4],\n r5 = this._r[5],\n r6 = this._r[6],\n r7 = this._r[7],\n r8 = this._r[8],\n r9 = this._r[9];\n\n while (bytes >= 16) {\n let t0 = m[mpos + 0] | m[mpos + 1] << 8; h0 += (t0) & 0x1fff;\n let t1 = m[mpos + 2] | m[mpos + 3] << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n let t2 = m[mpos + 4] | m[mpos + 5] << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;\n let t3 = m[mpos + 6] | m[mpos + 7] << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n let t4 = m[mpos + 8] | m[mpos + 9] << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;\n h5 += ((t4 >>> 1)) & 0x1fff;\n let t5 = m[mpos + 10] | m[mpos + 11] << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n let t6 = m[mpos + 12] | m[mpos + 13] << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;\n let t7 = m[mpos + 14] | m[mpos + 15] << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n h9 += ((t7 >>> 5)) | hibit;\n\n let c = 0;\n\n let d0 = c;\n d0 += h0 * r0;\n d0 += h1 * (5 * r9);\n d0 += h2 * (5 * r8);\n d0 += h3 * (5 * r7);\n d0 += h4 * (5 * r6);\n c = (d0 >>> 13); d0 &= 0x1fff;\n d0 += h5 * (5 * r5);\n d0 += h6 * (5 * r4);\n d0 += h7 * (5 * r3);\n d0 += h8 * (5 * r2);\n d0 += h9 * (5 * r1);\n c += (d0 >>> 13); d0 &= 0x1fff;\n\n let d1 = c;\n d1 += h0 * r1;\n d1 += h1 * r0;\n d1 += h2 * (5 * r9);\n d1 += h3 * (5 * r8);\n d1 += h4 * (5 * r7);\n c = (d1 >>> 13); d1 &= 0x1fff;\n d1 += h5 * (5 * r6);\n d1 += h6 * (5 * r5);\n d1 += h7 * (5 * r4);\n d1 += h8 * (5 * r3);\n d1 += h9 * (5 * r2);\n c += (d1 >>> 13); d1 &= 0x1fff;\n\n let d2 = c;\n d2 += h0 * r2;\n d2 += h1 * r1;\n d2 += h2 * r0;\n d2 += h3 * (5 * r9);\n d2 += h4 * (5 * r8);\n c = (d2 >>> 13); d2 &= 0x1fff;\n d2 += h5 * (5 * r7);\n d2 += h6 * (5 * r6);\n d2 += h7 * (5 * r5);\n d2 += h8 * (5 * r4);\n d2 += h9 * (5 * r3);\n c += (d2 >>> 13); d2 &= 0x1fff;\n\n let d3 = c;\n d3 += h0 * r3;\n d3 += h1 * r2;\n d3 += h2 * r1;\n d3 += h3 * r0;\n d3 += h4 * (5 * r9);\n c = (d3 >>> 13); d3 &= 0x1fff;\n d3 += h5 * (5 * r8);\n d3 += h6 * (5 * r7);\n d3 += h7 * (5 * r6);\n d3 += h8 * (5 * r5);\n d3 += h9 * (5 * r4);\n c += (d3 >>> 13); d3 &= 0x1fff;\n\n let d4 = c;\n d4 += h0 * r4;\n d4 += h1 * r3;\n d4 += h2 * r2;\n d4 += h3 * r1;\n d4 += h4 * r0;\n c = (d4 >>> 13); d4 &= 0x1fff;\n d4 += h5 * (5 * r9);\n d4 += h6 * (5 * r8);\n d4 += h7 * (5 * r7);\n d4 += h8 * (5 * r6);\n d4 += h9 * (5 * r5);\n c += (d4 >>> 13); d4 &= 0x1fff;\n\n let d5 = c;\n d5 += h0 * r5;\n d5 += h1 * r4;\n d5 += h2 * r3;\n d5 += h3 * r2;\n d5 += h4 * r1;\n c = (d5 >>> 13); d5 &= 0x1fff;\n d5 += h5 * r0;\n d5 += h6 * (5 * r9);\n d5 += h7 * (5 * r8);\n d5 += h8 * (5 * r7);\n d5 += h9 * (5 * r6);\n c += (d5 >>> 13); d5 &= 0x1fff;\n\n let d6 = c;\n d6 += h0 * r6;\n d6 += h1 * r5;\n d6 += h2 * r4;\n d6 += h3 * r3;\n d6 += h4 * r2;\n c = (d6 >>> 13); d6 &= 0x1fff;\n d6 += h5 * r1;\n d6 += h6 * r0;\n d6 += h7 * (5 * r9);\n d6 += h8 * (5 * r8);\n d6 += h9 * (5 * r7);\n c += (d6 >>> 13); d6 &= 0x1fff;\n\n let d7 = c;\n d7 += h0 * r7;\n d7 += h1 * r6;\n d7 += h2 * r5;\n d7 += h3 * r4;\n d7 += h4 * r3;\n c = (d7 >>> 13); d7 &= 0x1fff;\n d7 += h5 * r2;\n d7 += h6 * r1;\n d7 += h7 * r0;\n d7 += h8 * (5 * r9);\n d7 += h9 * (5 * r8);\n c += (d7 >>> 13); d7 &= 0x1fff;\n\n let d8 = c;\n d8 += h0 * r8;\n d8 += h1 * r7;\n d8 += h2 * r6;\n d8 += h3 * r5;\n d8 += h4 * r4;\n c = (d8 >>> 13); d8 &= 0x1fff;\n d8 += h5 * r3;\n d8 += h6 * r2;\n d8 += h7 * r1;\n d8 += h8 * r0;\n d8 += h9 * (5 * r9);\n c += (d8 >>> 13); d8 &= 0x1fff;\n\n let d9 = c;\n d9 += h0 * r9;\n d9 += h1 * r8;\n d9 += h2 * r7;\n d9 += h3 * r6;\n d9 += h4 * r5;\n c = (d9 >>> 13); d9 &= 0x1fff;\n d9 += h5 * r4;\n d9 += h6 * r3;\n d9 += h7 * r2;\n d9 += h8 * r1;\n d9 += h9 * r0;\n c += (d9 >>> 13); d9 &= 0x1fff;\n\n c = (((c << 2) + c)) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = (c >>> 13);\n d1 += c;\n\n h0 = d0;\n h1 = d1;\n h2 = d2;\n h3 = d3;\n h4 = d4;\n h5 = d5;\n h6 = d6;\n h7 = d7;\n h8 = d8;\n h9 = d9;\n\n mpos += 16;\n bytes -= 16;\n }\n this._h[0] = h0;\n this._h[1] = h1;\n this._h[2] = h2;\n this._h[3] = h3;\n this._h[4] = h4;\n this._h[5] = h5;\n this._h[6] = h6;\n this._h[7] = h7;\n this._h[8] = h8;\n this._h[9] = h9;\n }\n\n finish(mac: Uint8Array, macpos = 0): this {\n const g = new Uint16Array(10);\n let c: number;\n let mask: number;\n let f: number;\n let i: number;\n\n if (this._leftover) {\n i = this._leftover;\n this._buffer[i++] = 1;\n for (; i < 16; i++) {\n this._buffer[i] = 0;\n }\n this._fin = 1;\n this._blocks(this._buffer, 0, 16);\n }\n\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n for (i = 2; i < 10; i++) {\n this._h[i] += c;\n c = this._h[i] >>> 13;\n this._h[i] &= 0x1fff;\n }\n this._h[0] += (c * 5);\n c = this._h[0] >>> 13;\n this._h[0] &= 0x1fff;\n this._h[1] += c;\n c = this._h[1] >>> 13;\n this._h[1] &= 0x1fff;\n this._h[2] += c;\n\n g[0] = this._h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (i = 1; i < 10; i++) {\n g[i] = this._h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= (1 << 13);\n\n mask = (c ^ 1) - 1;\n for (i = 0; i < 10; i++) {\n g[i] &= mask;\n }\n mask = ~mask;\n for (i = 0; i < 10; i++) {\n this._h[i] = (this._h[i] & mask) | g[i];\n }\n\n this._h[0] = ((this._h[0]) | (this._h[1] << 13)) & 0xffff;\n this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;\n this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;\n this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;\n this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;\n this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;\n this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;\n this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;\n\n f = this._h[0] + this._pad[0];\n this._h[0] = f & 0xffff;\n for (i = 1; i < 8; i++) {\n f = (((this._h[i] + this._pad[i]) | 0) + (f >>> 16)) | 0;\n this._h[i] = f & 0xffff;\n }\n\n mac[macpos + 0] = this._h[0] >>> 0;\n mac[macpos + 1] = this._h[0] >>> 8;\n mac[macpos + 2] = this._h[1] >>> 0;\n mac[macpos + 3] = this._h[1] >>> 8;\n mac[macpos + 4] = this._h[2] >>> 0;\n mac[macpos + 5] = this._h[2] >>> 8;\n mac[macpos + 6] = this._h[3] >>> 0;\n mac[macpos + 7] = this._h[3] >>> 8;\n mac[macpos + 8] = this._h[4] >>> 0;\n mac[macpos + 9] = this._h[4] >>> 8;\n mac[macpos + 10] = this._h[5] >>> 0;\n mac[macpos + 11] = this._h[5] >>> 8;\n mac[macpos + 12] = this._h[6] >>> 0;\n mac[macpos + 13] = this._h[6] >>> 8;\n mac[macpos + 14] = this._h[7] >>> 0;\n mac[macpos + 15] = this._h[7] >>> 8;\n\n this._finished = true;\n return this;\n }\n\n update(m: Uint8Array): this {\n let mpos = 0;\n let bytes = m.length;\n let want: number;\n\n if (this._leftover) {\n want = (16 - this._leftover);\n if (want > bytes) {\n want = bytes;\n }\n for (let i = 0; i < want; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n bytes -= want;\n mpos += want;\n this._leftover += want;\n if (this._leftover < 16) {\n return this;\n }\n this._blocks(this._buffer, 0, 16);\n this._leftover = 0;\n }\n\n if (bytes >= 16) {\n want = bytes - (bytes % 16);\n this._blocks(m, mpos, want);\n mpos += want;\n bytes -= want;\n }\n\n if (bytes) {\n for (let i = 0; i < bytes; i++) {\n this._buffer[this._leftover + i] = m[mpos + i];\n }\n this._leftover += bytes;\n }\n\n return this;\n }\n\n digest(): Uint8Array {\n // TODO(dchest): it behaves differently than other hashes/HMAC,\n // because it throws when finished — others just return saved result.\n if (this._finished) {\n throw new Error(\"Poly1305 was finished\");\n }\n let mac = new Uint8Array(16);\n this.finish(mac);\n return mac;\n }\n\n clean(): this {\n wipe(this._buffer);\n wipe(this._r);\n wipe(this._h);\n wipe(this._pad);\n this._leftover = 0;\n this._fin = 0;\n this._finished = true; // mark as finished even if not\n return this;\n }\n}\n\n/**\n * Returns 16-byte authenticator of data using a one-time 32-byte key.\n *\n * Important: key should be used for only one message, it should never repeat.\n */\nexport function oneTimeAuth(key: Uint8Array, data: Uint8Array): Uint8Array {\n const h = new Poly1305(key);\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n\n/**\n * Returns true if two authenticators are 16-byte long and equal.\n * Uses contant-time comparison to avoid leaking timing information.\n */\nexport function equal(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== DIGEST_LENGTH || b.length !== DIGEST_LENGTH) {\n return false;\n }\n return constantTimeEqual(a, b);\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package random provides functions to access system's\n * cryptographically secure random byte generator.\n */\n\nimport { RandomSource } from \"./source\";\nimport { SystemRandomSource } from \"./source/system\";\nimport { readUint32LE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport { RandomSource } from \"./source\";\n\nexport const defaultRandomSource = new SystemRandomSource();\n\nexport function randomBytes(length: number, prng: RandomSource = defaultRandomSource): Uint8Array {\n return prng.randomBytes(length);\n}\n\n/**\n * Returns a uniformly random unsigned 32-bit integer.\n */\nexport function randomUint32(prng: RandomSource = defaultRandomSource): number {\n // Generate 4-byte random buffer.\n const buf = randomBytes(4, prng);\n\n // Convert bytes from buffer into a 32-bit integer.\n // It's not important which byte order to use, since\n // the result is random.\n const result = readUint32LE(buf);\n\n // Clean the buffer.\n wipe(buf);\n\n return result;\n}\n\n/** 62 alphanumeric characters for default charset of randomString() */\nconst ALPHANUMERIC = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Returns a uniform random string of the given length\n * with characters from the given charset.\n *\n * Charset must not have more than 256 characters.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomString(\n length: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n if (charset.length < 2) {\n throw new Error(\"randomString charset is too short\");\n }\n if (charset.length > 256) {\n throw new Error(\"randomString charset is too long\");\n }\n let out = '';\n const charsLen = charset.length;\n const maxByte = 256 - (256 % charsLen);\n while (length > 0) {\n const buf = randomBytes(Math.ceil(length * 256 / maxByte), prng);\n for (let i = 0; i < buf.length && length > 0; i++) {\n const randomByte = buf[i];\n if (randomByte < maxByte) {\n out += charset.charAt(randomByte % charsLen);\n length--;\n }\n }\n wipe(buf);\n }\n return out;\n}\n\n/**\n * Returns uniform random string containing at least the given\n * number of bits of entropy.\n *\n * For example, randomStringForEntropy(128) will return a 22-character\n * alphanumeric string, while randomStringForEntropy(128, \"0123456789\")\n * will return a 39-character numeric string, both will contain at\n * least 128 bits of entropy.\n *\n * Default charset generates case-sensitive alphanumeric\n * strings (0-9, A-Z, a-z).\n */\nexport function randomStringForEntropy(\n bits: number,\n charset = ALPHANUMERIC,\n prng: RandomSource = defaultRandomSource\n): string {\n const length = Math.ceil(bits / (Math.log(charset.length) / Math.LN2));\n return randomString(length, charset, prng);\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\n\nconst QUOTA = 65536;\n\nexport class BrowserRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto?: { getRandomValues: typeof window.crypto.getRandomValues };\n\n constructor() {\n const browserCrypto = typeof self !== 'undefined'\n ? (self.crypto || (self as { msCrypto?: any }).msCrypto) // IE11 has msCrypto\n : null;\n\n if (browserCrypto && browserCrypto.getRandomValues !== undefined) {\n this._crypto = browserCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Browser random byte generator is not available.\");\n }\n const out = new Uint8Array(length);\n for (let i = 0; i < out.length; i += QUOTA) {\n this._crypto.getRandomValues(out.subarray(i, i + Math.min(out.length - i, QUOTA)));\n }\n return out;\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { wipe } from \"@stablelib/wipe\";\n\ndeclare function require(name: string): any;\n\nexport class NodeRandomSource implements RandomSource {\n isAvailable = false;\n isInstantiated = false;\n\n private _crypto: { randomBytes(n: number): Uint8Array } | undefined;\n\n constructor() {\n if (typeof require !== \"undefined\") {\n const nodeCrypto = require(\"crypto\");\n if (nodeCrypto && nodeCrypto.randomBytes) {\n this._crypto = nodeCrypto;\n this.isAvailable = true;\n this.isInstantiated = true;\n }\n }\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable || !this._crypto) {\n throw new Error(\"Node.js random byte generator is not available.\");\n }\n\n // Get random bytes (result is Buffer).\n let buffer = this._crypto.randomBytes(length);\n\n // Make sure we got the length that we requested.\n if (buffer.length !== length) {\n throw new Error(\"NodeRandomSource: got fewer bytes than requested\");\n }\n\n // Allocate output array.\n const out = new Uint8Array(length);\n\n // Copy bytes from buffer to output.\n for (let i = 0; i < out.length; i++) {\n out[i] = buffer[i];\n }\n\n // Cleanup.\n wipe(buffer);\n\n return out;\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\nimport { RandomSource } from \"./\";\nimport { BrowserRandomSource } from \"./browser\";\nimport { NodeRandomSource } from \"./node\";\n\nexport class SystemRandomSource implements RandomSource {\n isAvailable = false;\n name = \"\";\n private _source: RandomSource;\n\n constructor() {\n // Try browser.\n this._source = new BrowserRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Browser\";\n return;\n }\n\n // If no browser source, try Node.\n this._source = new NodeRandomSource();\n if (this._source.isAvailable) {\n this.isAvailable = true;\n this.name = \"Node\";\n return;\n }\n\n // No sources, we're out of options.\n }\n\n randomBytes(length: number): Uint8Array {\n if (!this.isAvailable) {\n throw new Error(\"System random byte generator is not available.\");\n }\n return this._source.randomBytes(length);\n }\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package sha256 implements SHA-2-256 cryptographic hash function.\n */\n\nimport { SerializableHash } from \"@stablelib/hash\";\nimport { readUint32BE, writeUint32BE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 32;\nexport const BLOCK_SIZE = 64;\n\n/**\n * SHA2-256 cryptographic hash algorithm.\n */\nexport class SHA256 implements SerializableHash {\n /** Length of hash output */\n readonly digestLength: number = DIGEST_LENGTH;\n\n /** Block size */\n readonly blockSize: number = BLOCK_SIZE;\n\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n protected _state = new Int32Array(8); // hash state\n private _temp = new Int32Array(64); // temporary state\n private _buffer = new Uint8Array(128); // buffer for data to hash\n private _bufferLength = 0; // number of bytes in buffer\n private _bytesHashed = 0; // number of total bytes hashed\n private _finished = false; // indicates whether the hash was finalized\n\n constructor() {\n this.reset();\n }\n\n protected _initState() {\n this._state[0] = 0x6a09e667;\n this._state[1] = 0xbb67ae85;\n this._state[2] = 0x3c6ef372;\n this._state[3] = 0xa54ff53a;\n this._state[4] = 0x510e527f;\n this._state[5] = 0x9b05688c;\n this._state[6] = 0x1f83d9ab;\n this._state[7] = 0x5be0cd19;\n }\n\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n reset(): this {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans internal buffers and resets hash state.\n */\n clean() {\n wipe(this._buffer);\n wipe(this._temp);\n this.reset();\n }\n\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n update(data: Uint8Array, dataLength: number = data.length): this {\n if (this._finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n let dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < this.blockSize && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n }\n\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n finish(out: Uint8Array): this {\n if (!this._finished) {\n const bytesHashed = this._bytesHashed;\n const left = this._bufferLength;\n const bitLenHi = (bytesHashed / 0x20000000) | 0;\n const bitLenLo = bytesHashed << 3;\n const padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n\n this._buffer[left] = 0x80;\n for (let i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n\n hashBlocks(this._temp, this._state, this._buffer, 0, padLength);\n\n this._finished = true;\n }\n\n for (let i = 0; i < this.digestLength / 4; i++) {\n writeUint32BE(this._state[i], out, i * 4);\n }\n\n return this;\n }\n\n /**\n * Returns the final hash digest.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Returns hash state to be used with restoreState().\n * Only chain value is saved, not buffers or other\n * state variables.\n */\n saveState(): SavedState {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n state: new Int32Array(this._state),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization.\n * Restores state saved by saveState() and sets bytesHashed\n * to the given value.\n */\n restoreState(savedState: SavedState): this {\n this._state.set(savedState.state);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans state returned by saveState().\n */\n cleanSavedState(savedState: SavedState) {\n wipe(savedState.state);\n if (savedState.buffer) {\n wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n }\n}\n\nexport type SavedState = {\n state: Int32Array;\n buffer: Uint8Array | undefined;\n bufferLength: number;\n bytesHashed: number;\n};\n\n// Constants\nconst K = new Int32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\nfunction hashBlocks(w: Int32Array, v: Int32Array, p: Uint8Array, pos: number, len: number): number {\n while (len >= 64) {\n let a = v[0];\n let b = v[1];\n let c = v[2];\n let d = v[3];\n let e = v[4];\n let f = v[5];\n let g = v[6];\n let h = v[7];\n\n for (let i = 0; i < 16; i++) {\n let j = pos + i * 4;\n w[i] = readUint32BE(p, j);\n }\n\n for (let i = 16; i < 64; i++) {\n let u = w[i - 2];\n let t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n\n u = w[i - 15];\n let t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n\n for (let i = 0; i < 64; i++) {\n let t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n\n let t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n\n v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n\n pos += 64;\n len -= 64;\n }\n return pos;\n}\n\nexport function hash(data: Uint8Array): Uint8Array {\n const h = new SHA256();\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package sha512 implements SHA-2-512 cryptographic hash function.\n */\n\nimport { SerializableHash } from \"@stablelib/hash\";\nimport { readUint32BE, writeUint32BE } from \"@stablelib/binary\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const DIGEST_LENGTH = 64;\nexport const BLOCK_SIZE = 128;\n\n/**\n * SHA-2-512 cryptographic hash algorithm.\n */\nexport class SHA512 implements SerializableHash {\n /** Length of hash output */\n readonly digestLength: number = DIGEST_LENGTH;\n\n /** Block size */\n readonly blockSize: number = BLOCK_SIZE;\n\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n protected _stateHi = new Int32Array(8); // hash state, high bytes\n protected _stateLo = new Int32Array(8); // hash state, low bytes\n private _tempHi = new Int32Array(16); // temporary state, high bytes\n private _tempLo = new Int32Array(16); // temporary state, low bytes\n private _buffer = new Uint8Array(256); // buffer for data to hash\n private _bufferLength = 0; // number of bytes in buffer\n private _bytesHashed = 0; // number of total bytes hashed\n private _finished = false; // indicates whether the hash was finalized\n\n constructor() {\n this.reset();\n }\n\n protected _initState() {\n this._stateHi[0] = 0x6a09e667;\n this._stateHi[1] = 0xbb67ae85;\n this._stateHi[2] = 0x3c6ef372;\n this._stateHi[3] = 0xa54ff53a;\n this._stateHi[4] = 0x510e527f;\n this._stateHi[5] = 0x9b05688c;\n this._stateHi[6] = 0x1f83d9ab;\n this._stateHi[7] = 0x5be0cd19;\n\n this._stateLo[0] = 0xf3bcc908;\n this._stateLo[1] = 0x84caa73b;\n this._stateLo[2] = 0xfe94f82b;\n this._stateLo[3] = 0x5f1d36f1;\n this._stateLo[4] = 0xade682d1;\n this._stateLo[5] = 0x2b3e6c1f;\n this._stateLo[6] = 0xfb41bd6b;\n this._stateLo[7] = 0x137e2179;\n }\n\n /**\n * Resets hash state making it possible\n * to re-use this instance to hash other data.\n */\n reset(): this {\n this._initState();\n this._bufferLength = 0;\n this._bytesHashed = 0;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans internal buffers and resets hash state.\n */\n clean() {\n wipe(this._buffer);\n wipe(this._tempHi);\n wipe(this._tempLo);\n this.reset();\n }\n\n /**\n * Updates hash state with the given data.\n *\n * Throws error when trying to update already finalized hash:\n * instance must be reset to update it again.\n */\n update(data: Uint8Array, dataLength: number = data.length): this {\n if (this._finished) {\n throw new Error(\"SHA512: can't update because hash was finished.\");\n }\n let dataPos = 0;\n this._bytesHashed += dataLength;\n if (this._bufferLength > 0) {\n while (this._bufferLength < BLOCK_SIZE && dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this._bufferLength === this.blockSize) {\n hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo,\n this._buffer, 0, this.blockSize);\n this._bufferLength = 0;\n }\n }\n if (dataLength >= this.blockSize) {\n dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo,\n data, dataPos, dataLength);\n dataLength %= this.blockSize;\n }\n while (dataLength > 0) {\n this._buffer[this._bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n }\n\n /**\n * Finalizes hash state and puts hash into out.\n * If hash was already finalized, puts the same value.\n */\n finish(out: Uint8Array): this {\n if (!this._finished) {\n const bytesHashed = this._bytesHashed;\n const left = this._bufferLength;\n const bitLenHi = (bytesHashed / 0x20000000) | 0;\n const bitLenLo = bytesHashed << 3;\n const padLength = (bytesHashed % 128 < 112) ? 128 : 256;\n\n this._buffer[left] = 0x80;\n for (let i = left + 1; i < padLength - 8; i++) {\n this._buffer[i] = 0;\n }\n writeUint32BE(bitLenHi, this._buffer, padLength - 8);\n writeUint32BE(bitLenLo, this._buffer, padLength - 4);\n\n hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength);\n\n this._finished = true;\n }\n\n for (let i = 0; i < this.digestLength / 8; i++) {\n writeUint32BE(this._stateHi[i], out, i * 8);\n writeUint32BE(this._stateLo[i], out, i * 8 + 4);\n }\n\n return this;\n }\n\n /**\n * Returns the final hash digest.\n */\n digest(): Uint8Array {\n const out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization. Returns hash state to be\n * used with restoreState(). Only chain value is saved, not buffers or\n * other state variables.\n */\n saveState(): SavedState {\n if (this._finished) {\n throw new Error(\"SHA256: cannot save finished state\");\n }\n return {\n stateHi: new Int32Array(this._stateHi),\n stateLo: new Int32Array(this._stateLo),\n buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined,\n bufferLength: this._bufferLength,\n bytesHashed: this._bytesHashed\n };\n }\n\n /**\n * Function useful for HMAC/PBKDF2 optimization. Restores state saved by\n * saveState() and sets bytesHashed to the given value.\n */\n restoreState(savedState: SavedState): this {\n this._stateHi.set(savedState.stateHi);\n this._stateLo.set(savedState.stateLo);\n this._bufferLength = savedState.bufferLength;\n if (savedState.buffer) {\n this._buffer.set(savedState.buffer);\n }\n this._bytesHashed = savedState.bytesHashed;\n this._finished = false;\n return this;\n }\n\n /**\n * Cleans state returned by saveState().\n */\n cleanSavedState(savedState: SavedState) {\n wipe(savedState.stateHi);\n wipe(savedState.stateLo);\n if (savedState.buffer) {\n wipe(savedState.buffer);\n }\n savedState.bufferLength = 0;\n savedState.bytesHashed = 0;\n }\n}\n\nexport type SavedState = {\n stateHi: Int32Array;\n stateLo: Int32Array;\n buffer: Uint8Array | undefined;\n bufferLength: number;\n bytesHashed: number;\n};\n\n// Constants\nconst K = new Int32Array([\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n]);\n\n\nfunction hashBlocks(wh: Int32Array, wl: Int32Array, hh: Int32Array, hl: Int32Array,\n m: Uint8Array, pos: number, len: number): number {\n\n let ah0 = hh[0],\n ah1 = hh[1],\n ah2 = hh[2],\n ah3 = hh[3],\n ah4 = hh[4],\n ah5 = hh[5],\n ah6 = hh[6],\n ah7 = hh[7],\n\n al0 = hl[0],\n al1 = hl[1],\n al2 = hl[2],\n al3 = hl[3],\n al4 = hl[4],\n al5 = hl[5],\n al6 = hl[6],\n al7 = hl[7];\n\n let h: number, l: number;\n let th: number, tl: number;\n let a: number, b: number, c: number, d: number;\n\n while (len >= 128) {\n for (let i = 0; i < 16; i++) {\n const j = 8 * i + pos;\n wh[i] = readUint32BE(m, j);\n wl[i] = readUint32BE(m, j + 4);\n }\n for (let i = 0; i < 80; i++) {\n let bh0 = ah0;\n let bh1 = ah1;\n let bh2 = ah2;\n let bh3 = ah3;\n let bh4 = ah4;\n let bh5 = ah5;\n let bh6 = ah6;\n let bh7 = ah7;\n\n let bl0 = al0;\n let bl1 = al1;\n let bl2 = al2;\n let bl3 = al3;\n let bl4 = al4;\n let bl5 = al5;\n let bl6 = al6;\n let bl7 = al7;\n\n // add\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma1\n h = ((ah4 >>> 14) | (al4 << (32 - 14))) ^ ((ah4 >>> 18) |\n (al4 << (32 - 18))) ^ ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32))));\n l = ((al4 >>> 14) | (ah4 << (32 - 14))) ^ ((al4 >>> 18) |\n (ah4 << (32 - 18))) ^ ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Ch\n h = (ah4 & ah5) ^ (~ah4 & ah6);\n l = (al4 & al5) ^ (~al4 & al6);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // K\n h = K[i * 2];\n l = K[i * 2 + 1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // w\n h = wh[i % 16];\n l = wl[i % 16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n th = c & 0xffff | d << 16;\n tl = a & 0xffff | b << 16;\n\n // add\n h = th;\n l = tl;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n // Sigma0\n h = ((ah0 >>> 28) | (al0 << (32 - 28))) ^ ((al0 >>> (34 - 32)) |\n (ah0 << (32 - (34 - 32)))) ^ ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32))));\n l = ((al0 >>> 28) | (ah0 << (32 - 28))) ^ ((ah0 >>> (34 - 32)) |\n (al0 << (32 - (34 - 32)))) ^ ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32))));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // Maj\n h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);\n l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh7 = (c & 0xffff) | (d << 16);\n bl7 = (a & 0xffff) | (b << 16);\n\n // add\n h = bh3;\n l = bl3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = th;\n l = tl;\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n bh3 = (c & 0xffff) | (d << 16);\n bl3 = (a & 0xffff) | (b << 16);\n\n ah1 = bh0;\n ah2 = bh1;\n ah3 = bh2;\n ah4 = bh3;\n ah5 = bh4;\n ah6 = bh5;\n ah7 = bh6;\n ah0 = bh7;\n\n al1 = bl0;\n al2 = bl1;\n al3 = bl2;\n al4 = bl3;\n al5 = bl4;\n al6 = bl5;\n al7 = bl6;\n al0 = bl7;\n\n if (i % 16 === 15) {\n for (let j = 0; j < 16; j++) {\n // add\n h = wh[j];\n l = wl[j];\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = wh[(j + 9) % 16];\n l = wl[(j + 9) % 16];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma0\n th = wh[(j + 1) % 16];\n tl = wl[(j + 1) % 16];\n h = ((th >>> 1) | (tl << (32 - 1))) ^ ((th >>> 8) |\n (tl << (32 - 8))) ^ (th >>> 7);\n l = ((tl >>> 1) | (th << (32 - 1))) ^ ((tl >>> 8) |\n (th << (32 - 8))) ^ ((tl >>> 7) | (th << (32 - 7)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n // sigma1\n th = wh[(j + 14) % 16];\n tl = wl[(j + 14) % 16];\n h = ((th >>> 19) | (tl << (32 - 19))) ^ ((tl >>> (61 - 32)) |\n (th << (32 - (61 - 32)))) ^ (th >>> 6);\n l = ((tl >>> 19) | (th << (32 - 19))) ^ ((th >>> (61 - 32)) |\n (tl << (32 - (61 - 32)))) ^ ((tl >>> 6) | (th << (32 - 6)));\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n wh[j] = (c & 0xffff) | (d << 16);\n wl[j] = (a & 0xffff) | (b << 16);\n }\n }\n }\n\n // add\n h = ah0;\n l = al0;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[0];\n l = hl[0];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[0] = ah0 = (c & 0xffff) | (d << 16);\n hl[0] = al0 = (a & 0xffff) | (b << 16);\n\n h = ah1;\n l = al1;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[1];\n l = hl[1];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[1] = ah1 = (c & 0xffff) | (d << 16);\n hl[1] = al1 = (a & 0xffff) | (b << 16);\n\n h = ah2;\n l = al2;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[2];\n l = hl[2];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[2] = ah2 = (c & 0xffff) | (d << 16);\n hl[2] = al2 = (a & 0xffff) | (b << 16);\n\n h = ah3;\n l = al3;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[3];\n l = hl[3];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[3] = ah3 = (c & 0xffff) | (d << 16);\n hl[3] = al3 = (a & 0xffff) | (b << 16);\n\n h = ah4;\n l = al4;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[4];\n l = hl[4];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[4] = ah4 = (c & 0xffff) | (d << 16);\n hl[4] = al4 = (a & 0xffff) | (b << 16);\n\n h = ah5;\n l = al5;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[5];\n l = hl[5];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[5] = ah5 = (c & 0xffff) | (d << 16);\n hl[5] = al5 = (a & 0xffff) | (b << 16);\n\n h = ah6;\n l = al6;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[6];\n l = hl[6];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[6] = ah6 = (c & 0xffff) | (d << 16);\n hl[6] = al6 = (a & 0xffff) | (b << 16);\n\n h = ah7;\n l = al7;\n\n a = l & 0xffff; b = l >>> 16;\n c = h & 0xffff; d = h >>> 16;\n\n h = hh[7];\n l = hl[7];\n\n a += l & 0xffff; b += l >>> 16;\n c += h & 0xffff; d += h >>> 16;\n\n b += a >>> 16;\n c += b >>> 16;\n d += c >>> 16;\n\n hh[7] = ah7 = (c & 0xffff) | (d << 16);\n hl[7] = al7 = (a & 0xffff) | (b << 16);\n\n pos += 128;\n len -= 128;\n }\n\n return pos;\n}\n\nexport function hash(data: Uint8Array): Uint8Array {\n const h = new SHA512();\n h.update(data);\n const digest = h.digest();\n h.clean();\n return digest;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package wipe implements functions for zeroing arrays.\n */\n\nexport type NumericArray = number[] | Uint8Array | Int8Array | Uint16Array\n | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;\n\n/**\n * Sets all values in the given array to zero and returns it.\n *\n * The fact that it sets bytes to zero can be relied on.\n *\n * There is no guarantee that this function makes data disappear from memory,\n * as runtime implementation can, for example, have copying garbage collector\n * that will make copies of sensitive data before we wipe it. Or that an\n * operating system will write our data to swap or sleep image. Another thing\n * is that an optimizing compiler can remove calls to this function or make it\n * no-op. There's nothing we can do with it, so we just do our best and hope\n * that everything will be okay and good will triumph over evil.\n */\nexport function wipe(array: NumericArray): NumericArray {\n // Right now it's similar to array.fill(0). If it turns\n // out that runtimes optimize this call away, maybe\n // we can try something else.\n for (let i = 0; i < array.length; i++) {\n array[i] = 0;\n }\n return array;\n}\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package x25519 implements X25519 key agreement.\n */\n\nimport { randomBytes, RandomSource } from \"@stablelib/random\";\nimport { wipe } from \"@stablelib/wipe\";\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 32;\nexport const SHARED_KEY_LENGTH = 32;\n\n// TODO(dchest): some functions are copies of ../sign/ed25519.\n// Find a way to combine them without opening up to public.\n\n// Ported from TweetNaCl.js, which is ported from TweetNaCl\n// by Dmitry Chestnykh and Devi Mandiri.\n// Public domain.\n// https://tweetnacl.js.org\n\n// TweetNaCl contributors:\n// Daniel J. Bernstein, Bernard van Gastel, Wesley Janssen,\n// Tanja Lange, Peter Schwabe, Sjaak Smetsers.\n// Public domain.\n// https://tweetnacl.cr.yp.to/\n\ntype GF = Float64Array;\n\n// Returns new zero-filled 16-element GF (Float64Array).\n// If passed an array of numbers, prefills the returned\n// array with them.\n//\n// We use Float64Array, because we need 48-bit numbers\n// for this implementation.\nfunction gf(init?: number[]): GF {\n const r = new Float64Array(16);\n if (init) {\n for (let i = 0; i < init.length; i++) {\n r[i] = init[i];\n }\n }\n return r;\n}\n\n// Base point.\nconst _9 = new Uint8Array(32); _9[0] = 9;\n\nconst _121665 = gf([0xdb41, 1]);\n\nfunction car25519(o: GF) {\n let c = 1;\n for (let i = 0; i < 16; i++) {\n let v = o[i] + c + 65535;\n c = Math.floor(v / 65536);\n o[i] = v - c * 65536;\n }\n o[0] += c - 1 + 37 * (c - 1);\n}\n\nfunction sel25519(p: GF, q: GF, b: number) {\n const c = ~(b - 1);\n for (let i = 0; i < 16; i++) {\n const t = c & (p[i] ^ q[i]);\n p[i] ^= t;\n q[i] ^= t;\n }\n}\n\nfunction pack25519(o: Uint8Array, n: GF) {\n const m = gf();\n const t = gf();\n for (let i = 0; i < 16; i++) {\n t[i] = n[i];\n }\n car25519(t);\n car25519(t);\n car25519(t);\n for (let j = 0; j < 2; j++) {\n m[0] = t[0] - 0xffed;\n for (let i = 1; i < 15; i++) {\n m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);\n m[i - 1] &= 0xffff;\n }\n m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);\n const b = (m[15] >> 16) & 1;\n m[14] &= 0xffff;\n sel25519(t, m, 1 - b);\n }\n for (let i = 0; i < 16; i++) {\n o[2 * i] = t[i] & 0xff;\n o[2 * i + 1] = t[i] >> 8;\n }\n}\n\nfunction unpack25519(o: GF, n: Uint8Array) {\n for (let i = 0; i < 16; i++) {\n o[i] = n[2 * i] + (n[2 * i + 1] << 8);\n }\n o[15] &= 0x7fff;\n}\n\nfunction add(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] + b[i];\n }\n}\n\nfunction sub(o: GF, a: GF, b: GF) {\n for (let i = 0; i < 16; i++) {\n o[i] = a[i] - b[i];\n }\n}\n\nfunction mul(o: GF, a: GF, b: GF) {\n let v: number, c: number,\n t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,\n t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,\n t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,\n t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,\n b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11],\n b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n\n v = a[0];\n t0 += v * b0;\n t1 += v * b1;\n t2 += v * b2;\n t3 += v * b3;\n t4 += v * b4;\n t5 += v * b5;\n t6 += v * b6;\n t7 += v * b7;\n t8 += v * b8;\n t9 += v * b9;\n t10 += v * b10;\n t11 += v * b11;\n t12 += v * b12;\n t13 += v * b13;\n t14 += v * b14;\n t15 += v * b15;\n v = a[1];\n t1 += v * b0;\n t2 += v * b1;\n t3 += v * b2;\n t4 += v * b3;\n t5 += v * b4;\n t6 += v * b5;\n t7 += v * b6;\n t8 += v * b7;\n t9 += v * b8;\n t10 += v * b9;\n t11 += v * b10;\n t12 += v * b11;\n t13 += v * b12;\n t14 += v * b13;\n t15 += v * b14;\n t16 += v * b15;\n v = a[2];\n t2 += v * b0;\n t3 += v * b1;\n t4 += v * b2;\n t5 += v * b3;\n t6 += v * b4;\n t7 += v * b5;\n t8 += v * b6;\n t9 += v * b7;\n t10 += v * b8;\n t11 += v * b9;\n t12 += v * b10;\n t13 += v * b11;\n t14 += v * b12;\n t15 += v * b13;\n t16 += v * b14;\n t17 += v * b15;\n v = a[3];\n t3 += v * b0;\n t4 += v * b1;\n t5 += v * b2;\n t6 += v * b3;\n t7 += v * b4;\n t8 += v * b5;\n t9 += v * b6;\n t10 += v * b7;\n t11 += v * b8;\n t12 += v * b9;\n t13 += v * b10;\n t14 += v * b11;\n t15 += v * b12;\n t16 += v * b13;\n t17 += v * b14;\n t18 += v * b15;\n v = a[4];\n t4 += v * b0;\n t5 += v * b1;\n t6 += v * b2;\n t7 += v * b3;\n t8 += v * b4;\n t9 += v * b5;\n t10 += v * b6;\n t11 += v * b7;\n t12 += v * b8;\n t13 += v * b9;\n t14 += v * b10;\n t15 += v * b11;\n t16 += v * b12;\n t17 += v * b13;\n t18 += v * b14;\n t19 += v * b15;\n v = a[5];\n t5 += v * b0;\n t6 += v * b1;\n t7 += v * b2;\n t8 += v * b3;\n t9 += v * b4;\n t10 += v * b5;\n t11 += v * b6;\n t12 += v * b7;\n t13 += v * b8;\n t14 += v * b9;\n t15 += v * b10;\n t16 += v * b11;\n t17 += v * b12;\n t18 += v * b13;\n t19 += v * b14;\n t20 += v * b15;\n v = a[6];\n t6 += v * b0;\n t7 += v * b1;\n t8 += v * b2;\n t9 += v * b3;\n t10 += v * b4;\n t11 += v * b5;\n t12 += v * b6;\n t13 += v * b7;\n t14 += v * b8;\n t15 += v * b9;\n t16 += v * b10;\n t17 += v * b11;\n t18 += v * b12;\n t19 += v * b13;\n t20 += v * b14;\n t21 += v * b15;\n v = a[7];\n t7 += v * b0;\n t8 += v * b1;\n t9 += v * b2;\n t10 += v * b3;\n t11 += v * b4;\n t12 += v * b5;\n t13 += v * b6;\n t14 += v * b7;\n t15 += v * b8;\n t16 += v * b9;\n t17 += v * b10;\n t18 += v * b11;\n t19 += v * b12;\n t20 += v * b13;\n t21 += v * b14;\n t22 += v * b15;\n v = a[8];\n t8 += v * b0;\n t9 += v * b1;\n t10 += v * b2;\n t11 += v * b3;\n t12 += v * b4;\n t13 += v * b5;\n t14 += v * b6;\n t15 += v * b7;\n t16 += v * b8;\n t17 += v * b9;\n t18 += v * b10;\n t19 += v * b11;\n t20 += v * b12;\n t21 += v * b13;\n t22 += v * b14;\n t23 += v * b15;\n v = a[9];\n t9 += v * b0;\n t10 += v * b1;\n t11 += v * b2;\n t12 += v * b3;\n t13 += v * b4;\n t14 += v * b5;\n t15 += v * b6;\n t16 += v * b7;\n t17 += v * b8;\n t18 += v * b9;\n t19 += v * b10;\n t20 += v * b11;\n t21 += v * b12;\n t22 += v * b13;\n t23 += v * b14;\n t24 += v * b15;\n v = a[10];\n t10 += v * b0;\n t11 += v * b1;\n t12 += v * b2;\n t13 += v * b3;\n t14 += v * b4;\n t15 += v * b5;\n t16 += v * b6;\n t17 += v * b7;\n t18 += v * b8;\n t19 += v * b9;\n t20 += v * b10;\n t21 += v * b11;\n t22 += v * b12;\n t23 += v * b13;\n t24 += v * b14;\n t25 += v * b15;\n v = a[11];\n t11 += v * b0;\n t12 += v * b1;\n t13 += v * b2;\n t14 += v * b3;\n t15 += v * b4;\n t16 += v * b5;\n t17 += v * b6;\n t18 += v * b7;\n t19 += v * b8;\n t20 += v * b9;\n t21 += v * b10;\n t22 += v * b11;\n t23 += v * b12;\n t24 += v * b13;\n t25 += v * b14;\n t26 += v * b15;\n v = a[12];\n t12 += v * b0;\n t13 += v * b1;\n t14 += v * b2;\n t15 += v * b3;\n t16 += v * b4;\n t17 += v * b5;\n t18 += v * b6;\n t19 += v * b7;\n t20 += v * b8;\n t21 += v * b9;\n t22 += v * b10;\n t23 += v * b11;\n t24 += v * b12;\n t25 += v * b13;\n t26 += v * b14;\n t27 += v * b15;\n v = a[13];\n t13 += v * b0;\n t14 += v * b1;\n t15 += v * b2;\n t16 += v * b3;\n t17 += v * b4;\n t18 += v * b5;\n t19 += v * b6;\n t20 += v * b7;\n t21 += v * b8;\n t22 += v * b9;\n t23 += v * b10;\n t24 += v * b11;\n t25 += v * b12;\n t26 += v * b13;\n t27 += v * b14;\n t28 += v * b15;\n v = a[14];\n t14 += v * b0;\n t15 += v * b1;\n t16 += v * b2;\n t17 += v * b3;\n t18 += v * b4;\n t19 += v * b5;\n t20 += v * b6;\n t21 += v * b7;\n t22 += v * b8;\n t23 += v * b9;\n t24 += v * b10;\n t25 += v * b11;\n t26 += v * b12;\n t27 += v * b13;\n t28 += v * b14;\n t29 += v * b15;\n v = a[15];\n t15 += v * b0;\n t16 += v * b1;\n t17 += v * b2;\n t18 += v * b3;\n t19 += v * b4;\n t20 += v * b5;\n t21 += v * b6;\n t22 += v * b7;\n t23 += v * b8;\n t24 += v * b9;\n t25 += v * b10;\n t26 += v * b11;\n t27 += v * b12;\n t28 += v * b13;\n t29 += v * b14;\n t30 += v * b15;\n\n t0 += 38 * t16;\n t1 += 38 * t17;\n t2 += 38 * t18;\n t3 += 38 * t19;\n t4 += 38 * t20;\n t5 += 38 * t21;\n t6 += 38 * t22;\n t7 += 38 * t23;\n t8 += 38 * t24;\n t9 += 38 * t25;\n t10 += 38 * t26;\n t11 += 38 * t27;\n t12 += 38 * t28;\n t13 += 38 * t29;\n t14 += 38 * t30;\n // t15 left as is\n\n // first car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n // second car\n c = 1;\n v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;\n v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;\n v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;\n v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;\n v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;\n v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;\n v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;\n v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;\n v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;\n v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;\n v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;\n v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;\n v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;\n v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;\n v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;\n v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;\n t0 += c - 1 + 37 * (c - 1);\n\n o[0] = t0;\n o[1] = t1;\n o[2] = t2;\n o[3] = t3;\n o[4] = t4;\n o[5] = t5;\n o[6] = t6;\n o[7] = t7;\n o[8] = t8;\n o[9] = t9;\n o[10] = t10;\n o[11] = t11;\n o[12] = t12;\n o[13] = t13;\n o[14] = t14;\n o[15] = t15;\n}\n\nfunction square(o: GF, a: GF) {\n mul(o, a, a);\n}\n\nfunction inv25519(o: GF, inp: GF) {\n const c = gf();\n for (let i = 0; i < 16; i++) {\n c[i] = inp[i];\n }\n for (let i = 253; i >= 0; i--) {\n square(c, c);\n if (i !== 2 && i !== 4) {\n mul(c, c, inp);\n }\n }\n for (let i = 0; i < 16; i++) {\n o[i] = c[i];\n }\n}\n\nexport function scalarMult(n: Uint8Array, p: Uint8Array): Uint8Array {\n const z = new Uint8Array(32);\n const x = new Float64Array(80);\n const a = gf(), b = gf(), c = gf(),\n d = gf(), e = gf(), f = gf();\n\n for (let i = 0; i < 31; i++) {\n z[i] = n[i];\n }\n z[31] = (n[31] & 127) | 64;\n z[0] &= 248;\n\n unpack25519(x, p);\n\n for (let i = 0; i < 16; i++) {\n b[i] = x[i];\n }\n\n a[0] = d[0] = 1;\n\n for (let i = 254; i >= 0; --i) {\n const r = (z[i >>> 3] >>> (i & 7)) & 1;\n sel25519(a, b, r);\n sel25519(c, d, r);\n add(e, a, c);\n sub(a, a, c);\n add(c, b, d);\n sub(b, b, d);\n square(d, e);\n square(f, a);\n mul(a, c, a);\n mul(c, b, e);\n add(e, a, c);\n sub(a, a, c);\n square(b, a);\n sub(c, d, f);\n mul(a, c, _121665);\n add(a, a, d);\n mul(c, c, a);\n mul(a, d, f);\n mul(d, b, x);\n square(b, e);\n sel25519(a, b, r);\n sel25519(c, d, r);\n }\n for (let i = 0; i < 16; i++) {\n x[i + 16] = a[i];\n x[i + 32] = c[i];\n x[i + 48] = b[i];\n x[i + 64] = d[i];\n }\n const x32 = x.subarray(32);\n const x16 = x.subarray(16);\n inv25519(x32, x32);\n mul(x16, x16, x32);\n const q = new Uint8Array(32);\n pack25519(q, x16);\n return q;\n}\n\nexport function scalarMultBase(n: Uint8Array): Uint8Array {\n return scalarMult(n, _9);\n}\n\nexport interface KeyPair {\n publicKey: Uint8Array;\n secretKey: Uint8Array;\n}\n\nexport function generateKeyPairFromSeed(seed: Uint8Array): KeyPair {\n if (seed.length !== SECRET_KEY_LENGTH) {\n throw new Error(`x25519: seed must be ${SECRET_KEY_LENGTH} bytes`);\n }\n const secretKey = new Uint8Array(seed);\n const publicKey = scalarMultBase(secretKey);\n return {\n publicKey,\n secretKey\n };\n}\n\nexport function generateKeyPair(prng?: RandomSource): KeyPair {\n const seed = randomBytes(32, prng);\n const result = generateKeyPairFromSeed(seed);\n wipe(seed);\n return result;\n}\n\n/**\n * Returns a shared key between our secret key and a peer's public key.\n *\n * Throws an error if the given keys are of wrong length.\n *\n * If rejectZero is true throws if the calculated shared key is all-zero.\n * From RFC 7748:\n *\n * > Protocol designers using Diffie-Hellman over the curves defined in\n * > this document must not assume \"contributory behavior\". Specially,\n * > contributory behavior means that both parties' private keys\n * > contribute to the resulting shared key. Since curve25519 and\n * > curve448 have cofactors of 8 and 4 (respectively), an input point of\n * > small order will eliminate any contribution from the other party's\n * > private key. This situation can be detected by checking for the all-\n * > zero output, which implementations MAY do, as specified in Section 6.\n * > However, a large number of existing implementations do not do this.\n *\n * IMPORTANT: the returned key is a raw result of scalar multiplication.\n * To use it as a key material, hash it with a cryptographic hash function.\n */\nexport function sharedKey(mySecretKey: Uint8Array, theirPublicKey: Uint8Array, rejectZero = false): Uint8Array {\n if (mySecretKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect secret key length\");\n }\n if (theirPublicKey.length !== PUBLIC_KEY_LENGTH) {\n throw new Error(\"X25519: incorrect public key length\");\n }\n\n const result = scalarMult(mySecretKey, theirPublicKey);\n\n if (rejectZero) {\n let zeros = 0;\n for (let i = 0; i < result.length; i++) {\n zeros |= result[i];\n }\n if (zeros === 0) {\n throw new Error(\"X25519: invalid shared key\");\n }\n }\n\n return result;\n}\n",null,null,null,"/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.21';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function',\n INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading whitespace. */\n var reTrimStart = /^\\s+/;\n\n /** Used to match a single whitespace character. */\n var reWhitespace = /\\s/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /**\n * Used to validate the `validate` option in `_.template` variable.\n *\n * Forbids characters which could potentially change the meaning of the function argument definition:\n * - \"(),\" (modification of function parameters)\n * - \"=\" (default value)\n * - \"[]{}\" (destructuring of function parameters)\n * - \"/\" (beginning of a comment)\n * - whitespace\n */\n var reForbiddenIdentifierChars = /[()=,{}\\[\\]\\/\\s]/;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\n\n /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n }());\n\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\n function apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n }\n\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\n /**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\n function arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\n /**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\n /**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\n function baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\n\n /**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\n function baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n }\n\n /**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\n /**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\n\n /**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\n /**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\n function mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n }\n\n /**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\n /**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\n function setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n }\n\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\n /**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * A specialized version of `_.lastIndexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\n\n /**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\n function trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\n\n /**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\n\n /**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n }\n\n /**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\n\n /**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\n function hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n }\n\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n }\n\n /**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\n\n /**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\n\n /**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\n function listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n }\n\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\n\n /**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\n\n /**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\n\n /**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\n function mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n }\n\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n }\n\n /**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\n /**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\n /**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\n /**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function stackHas(key) {\n return this.__data__.has(key);\n }\n\n /**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\n function stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n }\n\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\n function arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\n\n /**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n }\n\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n /**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\n function baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseForRight = createBaseFor(true);\n\n /**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\n\n /**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\n function baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n }\n\n /**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\n\n /**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n function baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n }\n\n /**\n * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\n /**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\n\n /**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\n\n /**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n }\n\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\n function baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n }\n\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\n\n /**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\n\n /**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\n function baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n }\n\n /**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\n function baseLt(value, other) {\n return value < other;\n }\n\n /**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\n\n /**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\n function baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n }\n\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\n\n /**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\n function baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n }\n\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\n\n /**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n };\n\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\n\n /**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\n\n /**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\n\n /**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\n function castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n }\n\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\n\n /**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\n /**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n }\n\n /**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\n function createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n }\n\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n }\n\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\n function createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n }\n\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\n\n /**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\n\n /**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\n\n /**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\n\n /**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\n function getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n }\n\n /**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\n\n /**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\n function getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n };\n\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\n\n /**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\n function hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\n\n /**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n }\n\n /**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n }\n\n /**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\n function isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n }\n\n /**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\n function isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n }\n\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\n }\n\n /**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\n\n /**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\n /**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n }\n\n /**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\n function memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\n\n /**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\n function overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n }\n\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\n\n /**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\n\n /**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\n function shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n }\n\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\n\n /**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\n var stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n });\n\n /**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\n function toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\n function toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n }\n\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\n\n /**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\n\n /**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\n var sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n }\n\n // Expose `MapCache`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\n\n /**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n }\n\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

' + func(text) + '

';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

fred, barney, & pebbles

'\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\n /**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\n\n /**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n /**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\n\n /**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n }\n\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\n function isNil(value) {\n return value == null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n }\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\n\n /**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\n function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n }\n\n /**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\n\n /**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\n\n /**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\n\n /**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '\n * ```\n * @nocollapse\n * @category styles\n */\n static styles?: CSSResultGroup;\n\n /**\n * Returns a list of attributes corresponding to the registered properties.\n * @nocollapse\n * @category attributes\n */\n static get observedAttributes() {\n // Ensure we've created all properties\n this.finalize();\n // this.__attributeToPropertyMap is only undefined after finalize() in\n // ReactiveElement itself. ReactiveElement.observedAttributes is only\n // accessed with ReactiveElement as the receiver when a subclass or mixin\n // calls super.observedAttributes\n return (\n this.__attributeToPropertyMap && [...this.__attributeToPropertyMap.keys()]\n );\n }\n\n private __instanceProperties?: PropertyValues = undefined;\n\n /**\n * Creates a property accessor on the element prototype if one does not exist\n * and stores a {@linkcode PropertyDeclaration} for the property with the\n * given options. The property setter calls the property's `hasChanged`\n * property option or uses a strict identity check to determine whether or not\n * to request an update.\n *\n * This method may be overridden to customize properties; however,\n * when doing so, it's important to call `super.createProperty` to ensure\n * the property is setup correctly. This method calls\n * `getPropertyDescriptor` internally to get a descriptor to install.\n * To customize what properties do when they are get or set, override\n * `getPropertyDescriptor`. To customize the options for a property,\n * implement `createProperty` like this:\n *\n * ```ts\n * static createProperty(name, options) {\n * options = Object.assign(options, {myOption: true});\n * super.createProperty(name, options);\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n static createProperty(\n name: PropertyKey,\n options: PropertyDeclaration = defaultPropertyDeclaration\n ) {\n // If this is a state property, force the attribute to false.\n if (options.state) {\n (options as Mutable).attribute = false;\n }\n this.__prepare();\n this.elementProperties.set(name, options);\n if (!options.noAccessor) {\n const key = DEV_MODE\n ? // Use Symbol.for in dev mode to make it easier to maintain state\n // when doing HMR.\n Symbol.for(`${String(name)} (@property() cache)`)\n : Symbol();\n const descriptor = this.getPropertyDescriptor(name, key, options);\n if (descriptor !== undefined) {\n defineProperty(this.prototype, name, descriptor);\n }\n }\n }\n\n /**\n * Returns a property descriptor to be defined on the given named property.\n * If no descriptor is returned, the property will not become an accessor.\n * For example,\n *\n * ```ts\n * class MyElement extends LitElement {\n * static getPropertyDescriptor(name, key, options) {\n * const defaultDescriptor =\n * super.getPropertyDescriptor(name, key, options);\n * const setter = defaultDescriptor.set;\n * return {\n * get: defaultDescriptor.get,\n * set(value) {\n * setter.call(this, value);\n * // custom action.\n * },\n * configurable: true,\n * enumerable: true\n * }\n * }\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n protected static getPropertyDescriptor(\n name: PropertyKey,\n key: string | symbol,\n options: PropertyDeclaration\n ): PropertyDescriptor | undefined {\n const {get, set} = getOwnPropertyDescriptor(this.prototype, name) ?? {\n get(this: ReactiveElement) {\n return this[key as keyof typeof this];\n },\n set(this: ReactiveElement, v: unknown) {\n (this as unknown as Record)[key] = v;\n },\n };\n if (DEV_MODE && get == null) {\n if ('value' in (getOwnPropertyDescriptor(this.prototype, name) ?? {})) {\n throw new Error(\n `Field ${JSON.stringify(String(name))} on ` +\n `${this.name} was declared as a reactive property ` +\n `but it's actually declared as a value on the prototype. ` +\n `Usually this is due to using @property or @state on a method.`\n );\n }\n issueWarning(\n 'reactive-property-without-getter',\n `Field ${JSON.stringify(String(name))} on ` +\n `${this.name} was declared as a reactive property ` +\n `but it does not have a getter. This will be an error in a ` +\n `future version of Lit.`\n );\n }\n return {\n get(this: ReactiveElement) {\n return get?.call(this);\n },\n set(this: ReactiveElement, value: unknown) {\n const oldValue = get?.call(this);\n set!.call(this, value);\n this.requestUpdate(name, oldValue, options);\n },\n configurable: true,\n enumerable: true,\n };\n }\n\n /**\n * Returns the property options associated with the given property.\n * These options are defined with a `PropertyDeclaration` via the `properties`\n * object or the `@property` decorator and are registered in\n * `createProperty(...)`.\n *\n * Note, this method should be considered \"final\" and not overridden. To\n * customize the options for a given property, override\n * {@linkcode createProperty}.\n *\n * @nocollapse\n * @final\n * @category properties\n */\n static getPropertyOptions(name: PropertyKey) {\n return this.elementProperties.get(name) ?? defaultPropertyDeclaration;\n }\n\n // Temporary, until google3 is on TypeScript 5.2\n declare static [Symbol.metadata]: object & Record;\n\n /**\n * Initializes static own properties of the class used in bookkeeping\n * for element properties, initializers, etc.\n *\n * Can be called multiple times by code that needs to ensure these\n * properties exist before using them.\n *\n * This method ensures the superclass is finalized so that inherited\n * property metadata can be copied down.\n * @nocollapse\n */\n private static __prepare() {\n if (\n this.hasOwnProperty(JSCompiler_renameProperty('elementProperties', this))\n ) {\n // Already prepared\n return;\n }\n // Finalize any superclasses\n const superCtor = getPrototypeOf(this) as typeof ReactiveElement;\n superCtor.finalize();\n\n // Create own set of initializers for this class if any exist on the\n // superclass and copy them down. Note, for a small perf boost, avoid\n // creating initializers unless needed.\n if (superCtor._initializers !== undefined) {\n this._initializers = [...superCtor._initializers];\n }\n // Initialize elementProperties from the superclass\n this.elementProperties = new Map(superCtor.elementProperties);\n }\n\n /**\n * Finishes setting up the class so that it's ready to be registered\n * as a custom element and instantiated.\n *\n * This method is called by the ReactiveElement.observedAttributes getter.\n * If you override the observedAttributes getter, you must either call\n * super.observedAttributes to trigger finalization, or call finalize()\n * yourself.\n *\n * @nocollapse\n */\n protected static finalize() {\n if (this.hasOwnProperty(JSCompiler_renameProperty('finalized', this))) {\n return;\n }\n this.finalized = true;\n this.__prepare();\n\n // Create properties from the static properties block:\n if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {\n const props = this.properties;\n const propKeys = [\n ...getOwnPropertyNames(props),\n ...getOwnPropertySymbols(props),\n ] as Array;\n for (const p of propKeys) {\n this.createProperty(p, props[p]);\n }\n }\n\n // Create properties from standard decorator metadata:\n const metadata = this[Symbol.metadata];\n if (metadata !== null) {\n const properties = litPropertyMetadata.get(metadata);\n if (properties !== undefined) {\n for (const [p, options] of properties) {\n this.elementProperties.set(p, options);\n }\n }\n }\n\n // Create the attribute-to-property map\n this.__attributeToPropertyMap = new Map();\n for (const [p, options] of this.elementProperties) {\n const attr = this.__attributeNameForProperty(p, options);\n if (attr !== undefined) {\n this.__attributeToPropertyMap.set(attr, p);\n }\n }\n\n this.elementStyles = this.finalizeStyles(this.styles);\n\n if (DEV_MODE) {\n if (this.hasOwnProperty('createProperty')) {\n issueWarning(\n 'no-override-create-property',\n 'Overriding ReactiveElement.createProperty() is deprecated. ' +\n 'The override will not be called with standard decorators'\n );\n }\n if (this.hasOwnProperty('getPropertyDescriptor')) {\n issueWarning(\n 'no-override-get-property-descriptor',\n 'Overriding ReactiveElement.getPropertyDescriptor() is deprecated. ' +\n 'The override will not be called with standard decorators'\n );\n }\n }\n }\n\n /**\n * Options used when calling `attachShadow`. Set this property to customize\n * the options for the shadowRoot; for example, to create a closed\n * shadowRoot: `{mode: 'closed'}`.\n *\n * Note, these options are used in `createRenderRoot`. If this method\n * is customized, options should be respected if possible.\n * @nocollapse\n * @category rendering\n */\n static shadowRootOptions: ShadowRootInit = {mode: 'open'};\n\n /**\n * Takes the styles the user supplied via the `static styles` property and\n * returns the array of styles to apply to the element.\n * Override this method to integrate into a style management system.\n *\n * Styles are deduplicated preserving the _last_ instance in the list. This\n * is a performance optimization to avoid duplicated styles that can occur\n * especially when composing via subclassing. The last item is kept to try\n * to preserve the cascade order with the assumption that it's most important\n * that last added styles override previous styles.\n *\n * @nocollapse\n * @category styles\n */\n protected static finalizeStyles(\n styles?: CSSResultGroup\n ): Array {\n const elementStyles = [];\n if (Array.isArray(styles)) {\n // Dedupe the flattened array in reverse order to preserve the last items.\n // Casting to Array works around TS error that\n // appears to come from trying to flatten a type CSSResultArray.\n const set = new Set((styles as Array).flat(Infinity).reverse());\n // Then preserve original order by adding the set items in reverse order.\n for (const s of set) {\n elementStyles.unshift(getCompatibleStyle(s as CSSResultOrNative));\n }\n } else if (styles !== undefined) {\n elementStyles.push(getCompatibleStyle(styles));\n }\n return elementStyles;\n }\n\n /**\n * Node or ShadowRoot into which element DOM should be rendered. Defaults\n * to an open shadowRoot.\n * @category rendering\n */\n readonly renderRoot!: HTMLElement | DocumentFragment;\n\n /**\n * Returns the property name for the given attribute `name`.\n * @nocollapse\n */\n private static __attributeNameForProperty(\n name: PropertyKey,\n options: PropertyDeclaration\n ) {\n const attribute = options.attribute;\n return attribute === false\n ? undefined\n : typeof attribute === 'string'\n ? attribute\n : typeof name === 'string'\n ? name.toLowerCase()\n : undefined;\n }\n\n // Initialize to an unresolved Promise so we can make sure the element has\n // connected before first update.\n private __updatePromise!: Promise;\n\n /**\n * True if there is a pending update as a result of calling `requestUpdate()`.\n * Should only be read.\n * @category updates\n */\n isUpdatePending = false;\n\n /**\n * Is set to `true` after the first update. The element code cannot assume\n * that `renderRoot` exists before the element `hasUpdated`.\n * @category updates\n */\n hasUpdated = false;\n\n /**\n * Map with keys for any properties that have changed since the last\n * update cycle with previous values.\n *\n * @internal\n */\n _$changedProperties!: PropertyValues;\n\n /**\n * Properties that should be reflected when updated.\n */\n private __reflectingProperties?: Set;\n\n /**\n * Name of currently reflecting property\n */\n private __reflectingProperty: PropertyKey | null = null;\n\n /**\n * Set of controllers.\n */\n private __controllers?: Set;\n\n constructor() {\n super();\n this.__initialize();\n }\n\n /**\n * Internal only override point for customizing work done when elements\n * are constructed.\n */\n private __initialize() {\n this.__updatePromise = new Promise(\n (res) => (this.enableUpdating = res)\n );\n this._$changedProperties = new Map();\n // This enqueues a microtask that ust run before the first update, so it\n // must be called before requestUpdate()\n this.__saveInstanceProperties();\n // ensures first update will be caught by an early access of\n // `updateComplete`\n this.requestUpdate();\n (this.constructor as typeof ReactiveElement)._initializers?.forEach((i) =>\n i(this)\n );\n }\n\n /**\n * Registers a `ReactiveController` to participate in the element's reactive\n * update cycle. The element automatically calls into any registered\n * controllers during its lifecycle callbacks.\n *\n * If the element is connected when `addController()` is called, the\n * controller's `hostConnected()` callback will be immediately called.\n * @category controllers\n */\n addController(controller: ReactiveController) {\n (this.__controllers ??= new Set()).add(controller);\n // If a controller is added after the element has been connected,\n // call hostConnected. Note, re-using existence of `renderRoot` here\n // (which is set in connectedCallback) to avoid the need to track a\n // first connected state.\n if (this.renderRoot !== undefined && this.isConnected) {\n controller.hostConnected?.();\n }\n }\n\n /**\n * Removes a `ReactiveController` from the element.\n * @category controllers\n */\n removeController(controller: ReactiveController) {\n this.__controllers?.delete(controller);\n }\n\n /**\n * Fixes any properties set on the instance before upgrade time.\n * Otherwise these would shadow the accessor and break these properties.\n * The properties are stored in a Map which is played back after the\n * constructor runs. Note, on very old versions of Safari (<=9) or Chrome\n * (<=41), properties created for native platform properties like (`id` or\n * `name`) may not have default values set in the element constructor. On\n * these browsers native properties appear on instances and therefore their\n * default value will overwrite any element default (e.g. if the element sets\n * this.id = 'id' in the constructor, the 'id' will become '' since this is\n * the native platform default).\n */\n private __saveInstanceProperties() {\n const instanceProperties = new Map();\n const elementProperties = (this.constructor as typeof ReactiveElement)\n .elementProperties;\n for (const p of elementProperties.keys() as IterableIterator) {\n if (this.hasOwnProperty(p)) {\n instanceProperties.set(p, this[p]);\n delete this[p];\n }\n }\n if (instanceProperties.size > 0) {\n this.__instanceProperties = instanceProperties;\n }\n }\n\n /**\n * Returns the node into which the element should render and by default\n * creates and returns an open shadowRoot. Implement to customize where the\n * element's DOM is rendered. For example, to render into the element's\n * childNodes, return `this`.\n *\n * @return Returns a node into which to render.\n * @category rendering\n */\n protected createRenderRoot(): HTMLElement | DocumentFragment {\n const renderRoot =\n this.shadowRoot ??\n this.attachShadow(\n (this.constructor as typeof ReactiveElement).shadowRootOptions\n );\n adoptStyles(\n renderRoot,\n (this.constructor as typeof ReactiveElement).elementStyles\n );\n return renderRoot;\n }\n\n /**\n * On first connection, creates the element's renderRoot, sets up\n * element styling, and enables updating.\n * @category lifecycle\n */\n connectedCallback() {\n // Create renderRoot before controllers `hostConnected`\n (this as Mutable).renderRoot ??=\n this.createRenderRoot();\n this.enableUpdating(true);\n this.__controllers?.forEach((c) => c.hostConnected?.());\n }\n\n /**\n * Note, this method should be considered final and not overridden. It is\n * overridden on the element instance with a function that triggers the first\n * update.\n * @category updates\n */\n protected enableUpdating(_requestedUpdate: boolean) {}\n\n /**\n * Allows for `super.disconnectedCallback()` in extensions while\n * reserving the possibility of making non-breaking feature additions\n * when disconnecting at some point in the future.\n * @category lifecycle\n */\n disconnectedCallback() {\n this.__controllers?.forEach((c) => c.hostDisconnected?.());\n }\n\n /**\n * Synchronizes property values when attributes change.\n *\n * Specifically, when an attribute is set, the corresponding property is set.\n * You should rarely need to implement this callback. If this method is\n * overridden, `super.attributeChangedCallback(name, _old, value)` must be\n * called.\n *\n * See [using the lifecycle callbacks](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks)\n * on MDN for more information about the `attributeChangedCallback`.\n * @category attributes\n */\n attributeChangedCallback(\n name: string,\n _old: string | null,\n value: string | null\n ) {\n this._$attributeToProperty(name, value);\n }\n\n private __propertyToAttribute(name: PropertyKey, value: unknown) {\n const elemProperties: PropertyDeclarationMap = (\n this.constructor as typeof ReactiveElement\n ).elementProperties;\n const options = elemProperties.get(name)!;\n const attr = (\n this.constructor as typeof ReactiveElement\n ).__attributeNameForProperty(name, options);\n if (attr !== undefined && options.reflect === true) {\n const converter =\n (options.converter as ComplexAttributeConverter)?.toAttribute !==\n undefined\n ? (options.converter as ComplexAttributeConverter)\n : defaultConverter;\n const attrValue = converter.toAttribute!(value, options.type);\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'migration'\n ) &&\n attrValue === undefined\n ) {\n issueWarning(\n 'undefined-attribute-value',\n `The attribute value for the ${name as string} property is ` +\n `undefined on element ${this.localName}. The attribute will be ` +\n `removed, but in the previous version of \\`ReactiveElement\\`, ` +\n `the attribute would not have changed.`\n );\n }\n // Track if the property is being reflected to avoid\n // setting the property again via `attributeChangedCallback`. Note:\n // 1. this takes advantage of the fact that the callback is synchronous.\n // 2. will behave incorrectly if multiple attributes are in the reaction\n // stack at time of calling. However, since we process attributes\n // in `update` this should not be possible (or an extreme corner case\n // that we'd like to discover).\n // mark state reflecting\n this.__reflectingProperty = name;\n if (attrValue == null) {\n this.removeAttribute(attr);\n } else {\n this.setAttribute(attr, attrValue as string);\n }\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /** @internal */\n _$attributeToProperty(name: string, value: string | null) {\n const ctor = this.constructor as typeof ReactiveElement;\n // Note, hint this as an `AttributeMap` so closure clearly understands\n // the type; it has issues with tracking types through statics\n const propName = (ctor.__attributeToPropertyMap as AttributeMap).get(name);\n // Use tracking info to avoid reflecting a property value to an attribute\n // if it was just set because the attribute changed.\n if (propName !== undefined && this.__reflectingProperty !== propName) {\n const options = ctor.getPropertyOptions(propName);\n const converter =\n typeof options.converter === 'function'\n ? {fromAttribute: options.converter}\n : options.converter?.fromAttribute !== undefined\n ? options.converter\n : defaultConverter;\n // mark state reflecting\n this.__reflectingProperty = propName;\n this[propName as keyof this] = converter.fromAttribute!(\n value,\n options.type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any;\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /**\n * Requests an update which is processed asynchronously. This should be called\n * when an element should update based on some state not triggered by setting\n * a reactive property. In this case, pass no arguments. It should also be\n * called when manually implementing a property setter. In this case, pass the\n * property `name` and `oldValue` to ensure that any configured property\n * options are honored.\n *\n * @param name name of requesting property\n * @param oldValue old value of requesting property\n * @param options property options to use instead of the previously\n * configured options\n * @category updates\n */\n requestUpdate(\n name?: PropertyKey,\n oldValue?: unknown,\n options?: PropertyDeclaration\n ): void {\n // If we have a property key, perform property update steps.\n if (name !== undefined) {\n if (DEV_MODE && (name as unknown) instanceof Event) {\n issueWarning(\n ``,\n `The requestUpdate() method was called with an Event as the property name. This is probably a mistake caused by binding this.requestUpdate as an event listener. Instead bind a function that will call it with no arguments: () => this.requestUpdate()`\n );\n }\n options ??= (\n this.constructor as typeof ReactiveElement\n ).getPropertyOptions(name);\n const hasChanged = options.hasChanged ?? notEqual;\n const newValue = this[name as keyof this];\n if (hasChanged(newValue, oldValue)) {\n this._$changeProperty(name, oldValue, options);\n } else {\n // Abort the request if the property should not be considered changed.\n return;\n }\n }\n if (this.isUpdatePending === false) {\n this.__updatePromise = this.__enqueueUpdate();\n }\n }\n\n /**\n * @internal\n */\n _$changeProperty(\n name: PropertyKey,\n oldValue: unknown,\n options: PropertyDeclaration\n ) {\n // TODO (justinfagnani): Create a benchmark of Map.has() + Map.set(\n // vs just Map.set()\n if (!this._$changedProperties.has(name)) {\n this._$changedProperties.set(name, oldValue);\n }\n // Add to reflecting properties set.\n // Note, it's important that every change has a chance to add the\n // property to `__reflectingProperties`. This ensures setting\n // attribute + property reflects correctly.\n if (options.reflect === true && this.__reflectingProperty !== name) {\n (this.__reflectingProperties ??= new Set()).add(name);\n }\n }\n\n /**\n * Sets up the element to asynchronously update.\n */\n private async __enqueueUpdate() {\n this.isUpdatePending = true;\n try {\n // Ensure any previous update has resolved before updating.\n // This `await` also ensures that property changes are batched.\n await this.__updatePromise;\n } catch (e) {\n // Refire any previous errors async so they do not disrupt the update\n // cycle. Errors are refired so developers have a chance to observe\n // them, and this can be done by implementing\n // `window.onunhandledrejection`.\n Promise.reject(e);\n }\n const result = this.scheduleUpdate();\n // If `scheduleUpdate` returns a Promise, we await it. This is done to\n // enable coordinating updates with a scheduler. Note, the result is\n // checked to avoid delaying an additional microtask unless we need to.\n if (result != null) {\n await result;\n }\n return !this.isUpdatePending;\n }\n\n /**\n * Schedules an element update. You can override this method to change the\n * timing of updates by returning a Promise. The update will await the\n * returned Promise, and you should resolve the Promise to allow the update\n * to proceed. If this method is overridden, `super.scheduleUpdate()`\n * must be called.\n *\n * For instance, to schedule updates to occur just before the next frame:\n *\n * ```ts\n * override protected async scheduleUpdate(): Promise {\n * await new Promise((resolve) => requestAnimationFrame(() => resolve()));\n * super.scheduleUpdate();\n * }\n * ```\n * @category updates\n */\n protected scheduleUpdate(): void | Promise {\n const result = this.performUpdate();\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'async-perform-update'\n ) &&\n typeof (result as unknown as Promise | undefined)?.then ===\n 'function'\n ) {\n issueWarning(\n 'async-perform-update',\n `Element ${this.localName} returned a Promise from performUpdate(). ` +\n `This behavior is deprecated and will be removed in a future ` +\n `version of ReactiveElement.`\n );\n }\n return result;\n }\n\n /**\n * Performs an element update. Note, if an exception is thrown during the\n * update, `firstUpdated` and `updated` will not be called.\n *\n * Call `performUpdate()` to immediately process a pending update. This should\n * generally not be needed, but it can be done in rare cases when you need to\n * update synchronously.\n *\n * @category updates\n */\n protected performUpdate(): void {\n // Abort any update if one is not pending when this is called.\n // This can happen if `performUpdate` is called early to \"flush\"\n // the update.\n if (!this.isUpdatePending) {\n return;\n }\n debugLogEvent?.({kind: 'update'});\n if (!this.hasUpdated) {\n // Create renderRoot before first update. This occurs in `connectedCallback`\n // but is done here to support out of tree calls to `enableUpdating`/`performUpdate`.\n (this as Mutable).renderRoot ??=\n this.createRenderRoot();\n if (DEV_MODE) {\n // Produce warning if any reactive properties on the prototype are\n // shadowed by class fields. Instance fields set before upgrade are\n // deleted by this point, so any own property is caused by class field\n // initialization in the constructor.\n const ctor = this.constructor as typeof ReactiveElement;\n const shadowedProperties = [...ctor.elementProperties.keys()].filter(\n (p) => this.hasOwnProperty(p) && p in getPrototypeOf(this)\n );\n if (shadowedProperties.length) {\n throw new Error(\n `The following properties on element ${this.localName} will not ` +\n `trigger updates as expected because they are set using class ` +\n `fields: ${shadowedProperties.join(', ')}. ` +\n `Native class fields and some compiled output will overwrite ` +\n `accessors used for detecting changes. See ` +\n `https://lit.dev/msg/class-field-shadowing ` +\n `for more information.`\n );\n }\n }\n // Mixin instance properties once, if they exist.\n if (this.__instanceProperties) {\n // TODO (justinfagnani): should we use the stored value? Could a new value\n // have been set since we stored the own property value?\n for (const [p, value] of this.__instanceProperties) {\n this[p as keyof this] = value as this[keyof this];\n }\n this.__instanceProperties = undefined;\n }\n // Trigger initial value reflection and populate the initial\n // changedProperties map, but only for the case of experimental\n // decorators on accessors, which will not have already populated the\n // changedProperties map. We can't know if these accessors had\n // initializers, so we just set them anyway - a difference from\n // experimental decorators on fields and standard decorators on\n // auto-accessors.\n // For context why experimentalDecorators with auto accessors are handled\n // specifically also see:\n // https://github.com/lit/lit/pull/4183#issuecomment-1711959635\n const elementProperties = (this.constructor as typeof ReactiveElement)\n .elementProperties;\n if (elementProperties.size > 0) {\n for (const [p, options] of elementProperties) {\n if (\n options.wrapped === true &&\n !this._$changedProperties.has(p) &&\n this[p as keyof this] !== undefined\n ) {\n this._$changeProperty(p, this[p as keyof this], options);\n }\n }\n }\n }\n let shouldUpdate = false;\n const changedProperties = this._$changedProperties;\n try {\n shouldUpdate = this.shouldUpdate(changedProperties);\n if (shouldUpdate) {\n this.willUpdate(changedProperties);\n this.__controllers?.forEach((c) => c.hostUpdate?.());\n this.update(changedProperties);\n } else {\n this.__markUpdated();\n }\n } catch (e) {\n // Prevent `firstUpdated` and `updated` from running when there's an\n // update exception.\n shouldUpdate = false;\n // Ensure element can accept additional updates after an exception.\n this.__markUpdated();\n throw e;\n }\n // The update is no longer considered pending and further updates are now allowed.\n if (shouldUpdate) {\n this._$didUpdate(changedProperties);\n }\n }\n\n /**\n * Invoked before `update()` to compute values needed during the update.\n *\n * Implement `willUpdate` to compute property values that depend on other\n * properties and are used in the rest of the update process.\n *\n * ```ts\n * willUpdate(changedProperties) {\n * // only need to check changed properties for an expensive computation.\n * if (changedProperties.has('firstName') || changedProperties.has('lastName')) {\n * this.sha = computeSHA(`${this.firstName} ${this.lastName}`);\n * }\n * }\n *\n * render() {\n * return html`SHA: ${this.sha}`;\n * }\n * ```\n *\n * @category updates\n */\n protected willUpdate(_changedProperties: PropertyValues): void {}\n\n // Note, this is an override point for polyfill-support.\n // @internal\n _$didUpdate(changedProperties: PropertyValues) {\n this.__controllers?.forEach((c) => c.hostUpdated?.());\n if (!this.hasUpdated) {\n this.hasUpdated = true;\n this.firstUpdated(changedProperties);\n }\n this.updated(changedProperties);\n if (\n DEV_MODE &&\n this.isUpdatePending &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'change-in-update'\n )\n ) {\n issueWarning(\n 'change-in-update',\n `Element ${this.localName} scheduled an update ` +\n `(generally because a property was set) ` +\n `after an update completed, causing a new update to be scheduled. ` +\n `This is inefficient and should be avoided unless the next update ` +\n `can only be scheduled as a side effect of the previous update.`\n );\n }\n }\n\n private __markUpdated() {\n this._$changedProperties = new Map();\n this.isUpdatePending = false;\n }\n\n /**\n * Returns a Promise that resolves when the element has completed updating.\n * The Promise value is a boolean that is `true` if the element completed the\n * update without triggering another update. The Promise result is `false` if\n * a property was set inside `updated()`. If the Promise is rejected, an\n * exception was thrown during the update.\n *\n * To await additional asynchronous work, override the `getUpdateComplete`\n * method. For example, it is sometimes useful to await a rendered element\n * before fulfilling this Promise. To do this, first await\n * `super.getUpdateComplete()`, then any subsequent state.\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n get updateComplete(): Promise {\n return this.getUpdateComplete();\n }\n\n /**\n * Override point for the `updateComplete` promise.\n *\n * It is not safe to override the `updateComplete` getter directly due to a\n * limitation in TypeScript which means it is not possible to call a\n * superclass getter (e.g. `super.updateComplete.then(...)`) when the target\n * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).\n * This method should be overridden instead. For example:\n *\n * ```ts\n * class MyElement extends LitElement {\n * override async getUpdateComplete() {\n * const result = await super.getUpdateComplete();\n * await this._myChild.updateComplete;\n * return result;\n * }\n * }\n * ```\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n protected getUpdateComplete(): Promise {\n return this.__updatePromise;\n }\n\n /**\n * Controls whether or not `update()` should be called when the element requests\n * an update. By default, this method always returns `true`, but this can be\n * customized to control when to update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected shouldUpdate(_changedProperties: PropertyValues): boolean {\n return true;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes.\n * It can be overridden to render and keep updated element DOM.\n * Setting properties inside this method will *not* trigger\n * another update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected update(_changedProperties: PropertyValues) {\n // The forEach() expression will only run when when __reflectingProperties is\n // defined, and it returns undefined, setting __reflectingProperties to\n // undefined\n this.__reflectingProperties &&= this.__reflectingProperties.forEach((p) =>\n this.__propertyToAttribute(p, this[p as keyof this])\n ) as undefined;\n this.__markUpdated();\n }\n\n /**\n * Invoked whenever the element is updated. Implement to perform\n * post-updating tasks via DOM APIs, for example, focusing an element.\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected updated(_changedProperties: PropertyValues) {}\n\n /**\n * Invoked when the element is first updated. Implement to perform one time\n * work on the element after update.\n *\n * ```ts\n * firstUpdated() {\n * this.renderRoot.getElementById('my-text-area').focus();\n * }\n * ```\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected firstUpdated(_changedProperties: PropertyValues) {}\n}\n// Assigned here to work around a jscompiler bug with static fields\n// when compiling to ES5.\n// https://github.com/google/closure-compiler/issues/3177\n(ReactiveElement as unknown as Record)[\n JSCompiler_renameProperty('elementProperties', ReactiveElement)\n] = new Map();\n(ReactiveElement as unknown as Record)[\n JSCompiler_renameProperty('finalized', ReactiveElement)\n] = new Map();\n\n// Apply polyfills if available\npolyfillSupport?.({ReactiveElement});\n\n// Dev mode warnings...\nif (DEV_MODE) {\n // Default warning set.\n ReactiveElement.enabledWarnings = [\n 'change-in-update',\n 'async-perform-update',\n ];\n const ensureOwnWarnings = function (ctor: typeof ReactiveElement) {\n if (\n !ctor.hasOwnProperty(JSCompiler_renameProperty('enabledWarnings', ctor))\n ) {\n ctor.enabledWarnings = ctor.enabledWarnings!.slice();\n }\n };\n ReactiveElement.enableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n if (!this.enabledWarnings!.includes(warning)) {\n this.enabledWarnings!.push(warning);\n }\n };\n ReactiveElement.disableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n const i = this.enabledWarnings!.indexOf(warning);\n if (i >= 0) {\n this.enabledWarnings!.splice(i, 1);\n }\n };\n}\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for ReactiveElement usage.\n(global.reactiveElementVersions ??= []).push('2.0.4');\nif (DEV_MODE && global.reactiveElementVersions.length > 1) {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent('lit-debug', {\n detail: event,\n }),\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n // Issue a warning, if we haven't already.\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (!global.litIssuedWarnings!.has(warning)) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`,\n );\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? (global.ShadyDOM!.wrap as (node: T) => T)\n : (node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute',\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute',\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`,\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with /g;\n/**\n * Comments not started with ')\n return {\n type: 'comment',\n comment: endIndex !== -1 ? tag.slice(4, endIndex) : '',\n }\n }\n }\n\n const reg = new RegExp(attrRE)\n let result = null\n for (;;) {\n result = reg.exec(tag)\n\n if (result === null) {\n break\n }\n\n if (!result[0].trim()) {\n continue\n }\n\n if (result[1]) {\n const attr = result[1].trim()\n let arr = [attr, '']\n\n if (attr.indexOf('=') > -1) {\n arr = attr.split('=')\n }\n\n res.attrs[arr[0]] = arr[1]\n reg.lastIndex--\n } else if (result[2]) {\n res.attrs[result[2]] = result[3].trim().substring(1, result[3].length - 1)\n }\n }\n\n return res\n}\n","import parseTag from './parse-tag'\n\nconst tagRE = /<[a-zA-Z0-9\\-\\!\\/](?:\"[^\"]*\"|'[^']*'|[^'\">])*>/g\nconst whitespaceRE = /^\\s*$/\n\n// re-used obj for quick lookups of components\nconst empty = Object.create(null)\n\nexport default function parse(html, options) {\n options || (options = {})\n options.components || (options.components = empty)\n const result = []\n const arr = []\n let current\n let level = -1\n let inComponent = false\n\n // handle text at top level\n if (html.indexOf('<') !== 0) {\n var end = html.indexOf('<')\n result.push({\n type: 'text',\n content: end === -1 ? html : html.substring(0, end),\n })\n }\n\n html.replace(tagRE, function (tag, index) {\n if (inComponent) {\n if (tag !== '') {\n return\n } else {\n inComponent = false\n }\n }\n const isOpen = tag.charAt(1) !== '/'\n const isComment = tag.startsWith(''\n return buff\n }\n}\n\nexport default function (doc) {\n return doc.reduce(function (token, rootEl) {\n return token + stringify('', rootEl)\n }, '')\n}\n","import parse from './parse'\nimport stringify from './stringify'\n\nexport default {\n parse,\n stringify,\n}\n","export const warn = (...args) => {\n if (console?.warn) {\n if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`;\n console.warn(...args);\n }\n};\nconst alreadyWarned = {};\nexport const warnOnce = (...args) => {\n if (isString(args[0]) && alreadyWarned[args[0]]) return;\n if (isString(args[0])) alreadyWarned[args[0]] = new Date();\n warn(...args);\n};\nconst loadedClb = (i18n, cb) => () => {\n if (i18n.isInitialized) {\n cb();\n } else {\n const initialized = () => {\n setTimeout(() => {\n i18n.off('initialized', initialized);\n }, 0);\n cb();\n };\n i18n.on('initialized', initialized);\n }\n};\nexport const loadNamespaces = (i18n, ns, cb) => {\n i18n.loadNamespaces(ns, loadedClb(i18n, cb));\n};\nexport const loadLanguages = (i18n, lng, ns, cb) => {\n if (isString(ns)) ns = [ns];\n ns.forEach(n => {\n if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);\n });\n i18n.loadLanguages(lng, loadedClb(i18n, cb));\n};\nexport const hasLoadedNamespace = (ns, i18n, options = {}) => {\n if (!i18n.languages || !i18n.languages.length) {\n warnOnce('i18n.languages were undefined or empty', i18n.languages);\n return true;\n }\n return i18n.hasLoadedNamespace(ns, {\n lng: options.lng,\n precheck: (i18nInstance, loadNotPending) => {\n if (options.bindI18n?.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;\n }\n });\n};\nexport const getDisplayName = Component => Component.displayName || Component.name || (isString(Component) && Component.length > 0 ? Component : 'Unknown');\nexport const isString = obj => typeof obj === 'string';\nexport const isObject = obj => typeof obj === 'object' && obj !== null;","const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;\nconst htmlEntities = {\n '&': '&',\n '&': '&',\n '<': '<',\n '<': '<',\n '>': '>',\n '>': '>',\n ''': \"'\",\n ''': \"'\",\n '"': '\"',\n '"': '\"',\n ' ': ' ',\n ' ': ' ',\n '©': '©',\n '©': '©',\n '®': '®',\n '®': '®',\n '…': '…',\n '…': '…',\n '/': '/',\n '/': '/'\n};\nconst unescapeHtmlEntity = m => htmlEntities[m];\nexport const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);","import { unescape } from './unescape.js';\nlet defaultOptions = {\n bindI18n: 'languageChanged',\n bindI18nStore: '',\n transEmptyNodeValue: '',\n transSupportBasicHtmlNodes: true,\n transWrapTextNodes: '',\n transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],\n useSuspense: true,\n unescape\n};\nexport const setDefaults = (options = {}) => {\n defaultOptions = {\n ...defaultOptions,\n ...options\n };\n};\nexport const getDefaults = () => defaultOptions;","let i18nInstance;\nexport const setI18n = instance => {\n i18nInstance = instance;\n};\nexport const getI18n = () => i18nInstance;","import { Fragment, isValidElement, cloneElement, createElement, Children } from 'react';\nimport HTML from 'html-parse-stringify';\nimport { isObject, isString, warn, warnOnce } from './utils.js';\nimport { getDefaults } from './defaults.js';\nimport { getI18n } from './i18nInstance.js';\nconst hasChildren = (node, checkLength) => {\n if (!node) return false;\n const base = node.props?.children ?? node.children;\n if (checkLength) return base.length > 0;\n return !!base;\n};\nconst getChildren = node => {\n if (!node) return [];\n const children = node.props?.children ?? node.children;\n return node.props?.i18nIsDynamicList ? getAsArray(children) : children;\n};\nconst hasValidReactChildren = children => Array.isArray(children) && children.every(isValidElement);\nconst getAsArray = data => Array.isArray(data) ? data : [data];\nconst mergeProps = (source, target) => {\n const newTarget = {\n ...target\n };\n newTarget.props = Object.assign(source.props, target.props);\n return newTarget;\n};\nexport const nodesToString = (children, i18nOptions) => {\n if (!children) return '';\n let stringNode = '';\n const childrenArray = getAsArray(children);\n const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : [];\n childrenArray.forEach((child, childIndex) => {\n if (isString(child)) {\n stringNode += `${child}`;\n } else if (isValidElement(child)) {\n const {\n props,\n type\n } = child;\n const childPropsCount = Object.keys(props).length;\n const shouldKeepChild = keepArray.indexOf(type) > -1;\n const childChildren = props.children;\n if (!childChildren && shouldKeepChild && !childPropsCount) {\n stringNode += `<${type}/>`;\n } else if (!childChildren && (!shouldKeepChild || childPropsCount) || props.i18nIsDynamicList) {\n stringNode += `<${childIndex}>`;\n } else if (shouldKeepChild && childPropsCount === 1 && isString(childChildren)) {\n stringNode += `<${type}>${childChildren}`;\n } else {\n const content = nodesToString(childChildren, i18nOptions);\n stringNode += `<${childIndex}>${content}`;\n }\n } else if (child === null) {\n warn(`Trans: the passed in value is invalid - seems you passed in a null child.`);\n } else if (isObject(child)) {\n const {\n format,\n ...clone\n } = child;\n const keys = Object.keys(clone);\n if (keys.length === 1) {\n const value = format ? `${keys[0]}, ${format}` : keys[0];\n stringNode += `{{${value}}}`;\n } else {\n warn(`react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.`, child);\n }\n } else {\n warn(`Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.`, child);\n }\n });\n return stringNode;\n};\nconst renderNodes = (children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) => {\n if (targetString === '') return [];\n const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];\n const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString);\n if (!children && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString];\n const data = {};\n const getData = childs => {\n const childrenArray = getAsArray(childs);\n childrenArray.forEach(child => {\n if (isString(child)) return;\n if (hasChildren(child)) getData(getChildren(child));else if (isObject(child) && !isValidElement(child)) Object.assign(data, child);\n });\n };\n getData(children);\n const ast = HTML.parse(`<0>${targetString}`);\n const opts = {\n ...data,\n ...combinedTOpts\n };\n const renderInner = (child, node, rootReactNode) => {\n const childs = getChildren(child);\n const mappedChildren = mapAST(childs, node.children, rootReactNode);\n return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren;\n };\n const pushTranslatedJSX = (child, inner, mem, i, isVoid) => {\n if (child.dummy) {\n child.children = inner;\n mem.push(cloneElement(child, {\n key: i\n }, isVoid ? undefined : inner));\n } else {\n mem.push(...Children.map([child], c => {\n const props = {\n ...c.props\n };\n delete props.i18nIsDynamicList;\n return createElement(c.type, {\n ...props,\n key: i,\n ref: c.ref\n }, isVoid ? null : inner);\n }));\n }\n };\n const mapAST = (reactNode, astNode, rootReactNode) => {\n const reactNodes = getAsArray(reactNode);\n const astNodes = getAsArray(astNode);\n return astNodes.reduce((mem, node, i) => {\n const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);\n if (node.type === 'tag') {\n let tmp = reactNodes[parseInt(node.name, 10)];\n if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name];\n if (!tmp) tmp = {};\n const child = Object.keys(node.attrs).length !== 0 ? mergeProps({\n props: node.attrs\n }, tmp) : tmp;\n const isElement = isValidElement(child);\n const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;\n const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && isObject(child) && child.dummy && !isElement;\n const isKnownComponent = isObject(children) && Object.hasOwnProperty.call(children, node.name);\n if (isString(child)) {\n const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);\n mem.push(value);\n } else if (hasChildren(child) || isValidTranslationWithChildren) {\n const inner = renderInner(child, node, rootReactNode);\n pushTranslatedJSX(child, inner, mem, i);\n } else if (isEmptyTransWithHTML) {\n const inner = mapAST(reactNodes, node.children, rootReactNode);\n pushTranslatedJSX(child, inner, mem, i);\n } else if (Number.isNaN(parseFloat(node.name))) {\n if (isKnownComponent) {\n const inner = renderInner(child, node, rootReactNode);\n pushTranslatedJSX(child, inner, mem, i, node.voidElement);\n } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {\n if (node.voidElement) {\n mem.push(createElement(node.name, {\n key: `${node.name}-${i}`\n }));\n } else {\n const inner = mapAST(reactNodes, node.children, rootReactNode);\n mem.push(createElement(node.name, {\n key: `${node.name}-${i}`\n }, inner));\n }\n } else if (node.voidElement) {\n mem.push(`<${node.name} />`);\n } else {\n const inner = mapAST(reactNodes, node.children, rootReactNode);\n mem.push(`<${node.name}>${inner}`);\n }\n } else if (isObject(child) && !isElement) {\n const content = node.children[0] ? translationContent : null;\n if (content) mem.push(content);\n } else {\n pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent);\n }\n } else if (node.type === 'text') {\n const wrapTextNodes = i18nOptions.transWrapTextNodes;\n const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);\n if (wrapTextNodes) {\n mem.push(createElement(wrapTextNodes, {\n key: `${node.name}-${i}`\n }, content));\n } else {\n mem.push(content);\n }\n }\n return mem;\n }, []);\n };\n const result = mapAST([{\n dummy: true,\n children: children || []\n }], ast, getAsArray(children || []));\n return getChildren(result[0]);\n};\nexport function Trans({\n children,\n count,\n parent,\n i18nKey,\n context,\n tOptions = {},\n values,\n defaults,\n components,\n ns,\n i18n: i18nFromProps,\n t: tFromProps,\n shouldUnescape,\n ...additionalProps\n}) {\n const i18n = i18nFromProps || getI18n();\n if (!i18n) {\n warnOnce('You will need to pass in an i18next instance by using i18nextReactModule');\n return children;\n }\n const t = tFromProps || i18n.t.bind(i18n) || (k => k);\n const reactI18nextOptions = {\n ...getDefaults(),\n ...i18n.options?.react\n };\n let namespaces = ns || t.ns || i18n.options?.defaultNS;\n namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];\n const nodeAsString = nodesToString(children, reactI18nextOptions);\n const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || i18nKey;\n const {\n hashTransKey\n } = reactI18nextOptions;\n const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue);\n if (i18n.options?.interpolation?.defaultVariables) {\n values = values && Object.keys(values).length > 0 ? {\n ...values,\n ...i18n.options.interpolation.defaultVariables\n } : {\n ...i18n.options.interpolation.defaultVariables\n };\n }\n const interpolationOverride = values || count !== undefined && !i18n.options?.interpolation?.alwaysFormat || !children ? tOptions.interpolation : {\n interpolation: {\n ...tOptions.interpolation,\n prefix: '#$?',\n suffix: '?$#'\n }\n };\n const combinedTOpts = {\n ...tOptions,\n context: context || tOptions.context,\n count,\n ...values,\n ...interpolationOverride,\n defaultValue,\n ns: namespaces\n };\n const translation = key ? t(key, combinedTOpts) : defaultValue;\n if (components) {\n Object.keys(components).forEach(c => {\n const comp = components[c];\n if (typeof comp.type === 'function' || !comp.props || !comp.props.children || translation.indexOf(`${c}/>`) < 0 && translation.indexOf(`${c} />`) < 0) return;\n function Componentized() {\n return createElement(Fragment, null, comp);\n }\n components[c] = createElement(Componentized);\n });\n }\n const content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);\n const useAsParent = parent ?? reactI18nextOptions.defaultTransParent;\n return useAsParent ? createElement(useAsParent, additionalProps, content) : content;\n}","import { setDefaults } from './defaults.js';\nimport { setI18n } from './i18nInstance.js';\nexport const initReactI18next = {\n type: '3rdParty',\n init(instance) {\n setDefaults(instance.options.react);\n setI18n(instance);\n }\n};","import { createContext } from 'react';\nimport { getDefaults, setDefaults } from './defaults.js';\nimport { getI18n, setI18n } from './i18nInstance.js';\nimport { initReactI18next } from './initReactI18next.js';\nexport { getDefaults, setDefaults, getI18n, setI18n, initReactI18next };\nexport const I18nContext = createContext();\nexport class ReportNamespaces {\n constructor() {\n this.usedNamespaces = {};\n }\n addUsedNamespaces(namespaces) {\n namespaces.forEach(ns => {\n this.usedNamespaces[ns] ??= true;\n });\n }\n getUsedNamespaces() {\n return Object.keys(this.usedNamespaces);\n }\n}\nexport const composeInitialProps = ForComponent => async ctx => {\n const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {};\n const i18nInitialProps = getInitialProps();\n return {\n ...componentsInitialProps,\n ...i18nInitialProps\n };\n};\nexport const getInitialProps = () => {\n const i18n = getI18n();\n const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? [];\n const ret = {};\n const initialI18nStore = {};\n i18n.languages.forEach(l => {\n initialI18nStore[l] = {};\n namespaces.forEach(ns => {\n initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};\n });\n });\n ret.initialI18nStore = initialI18nStore;\n ret.initialLanguage = i18n.language;\n return ret;\n};","import { useContext } from 'react';\nimport { nodesToString, Trans as TransWithoutContext } from './TransWithoutContext.js';\nimport { getI18n, I18nContext } from './context.js';\nexport { nodesToString };\nexport function Trans({\n children,\n count,\n parent,\n i18nKey,\n context,\n tOptions = {},\n values,\n defaults,\n components,\n ns,\n i18n: i18nFromProps,\n t: tFromProps,\n shouldUnescape,\n ...additionalProps\n}) {\n const {\n i18n: i18nFromContext,\n defaultNS: defaultNSFromContext\n } = useContext(I18nContext) || {};\n const i18n = i18nFromProps || i18nFromContext || getI18n();\n const t = tFromProps || i18n?.t.bind(i18n);\n return TransWithoutContext({\n children,\n count,\n parent,\n i18nKey,\n context,\n tOptions,\n values,\n defaults,\n components,\n ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,\n i18n,\n t: tFromProps,\n shouldUnescape,\n ...additionalProps\n });\n}","import { useState, useEffect, useContext, useRef, useCallback } from 'react';\nimport { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context.js';\nimport { warnOnce, loadNamespaces, loadLanguages, hasLoadedNamespace, isString, isObject } from './utils.js';\nconst usePrevious = (value, ignore) => {\n const ref = useRef();\n useEffect(() => {\n ref.current = ignore ? ref.current : value;\n }, [value, ignore]);\n return ref.current;\n};\nconst alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);\nconst useMemoizedT = (i18n, language, namespace, keyPrefix) => useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);\nexport const useTranslation = (ns, props = {}) => {\n const {\n i18n: i18nFromProps\n } = props;\n const {\n i18n: i18nFromContext,\n defaultNS: defaultNSFromContext\n } = useContext(I18nContext) || {};\n const i18n = i18nFromProps || i18nFromContext || getI18n();\n if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();\n if (!i18n) {\n warnOnce('You will need to pass in an i18next instance by using initReactI18next');\n const notReadyT = (k, optsOrDefaultValue) => {\n if (isString(optsOrDefaultValue)) return optsOrDefaultValue;\n if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;\n return Array.isArray(k) ? k[k.length - 1] : k;\n };\n const retNotReady = [notReadyT, {}, false];\n retNotReady.t = notReadyT;\n retNotReady.i18n = {};\n retNotReady.ready = false;\n return retNotReady;\n }\n if (i18n.options.react?.wait) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');\n const i18nOptions = {\n ...getDefaults(),\n ...i18n.options.react,\n ...props\n };\n const {\n useSuspense,\n keyPrefix\n } = i18nOptions;\n let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS;\n namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];\n i18n.reportNamespaces.addUsedNamespaces?.(namespaces);\n const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));\n const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);\n const getT = () => memoGetT;\n const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);\n const [t, setT] = useState(getT);\n let joinedNS = namespaces.join();\n if (props.lng) joinedNS = `${props.lng}${joinedNS}`;\n const previousJoinedNS = usePrevious(joinedNS);\n const isMounted = useRef(true);\n useEffect(() => {\n const {\n bindI18n,\n bindI18nStore\n } = i18nOptions;\n isMounted.current = true;\n if (!ready && !useSuspense) {\n if (props.lng) {\n loadLanguages(i18n, props.lng, namespaces, () => {\n if (isMounted.current) setT(getNewT);\n });\n } else {\n loadNamespaces(i18n, namespaces, () => {\n if (isMounted.current) setT(getNewT);\n });\n }\n }\n if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {\n setT(getNewT);\n }\n const boundReset = () => {\n if (isMounted.current) setT(getNewT);\n };\n if (bindI18n) i18n?.on(bindI18n, boundReset);\n if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset);\n return () => {\n isMounted.current = false;\n if (i18n) bindI18n?.split(' ').forEach(e => i18n.off(e, boundReset));\n if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));\n };\n }, [i18n, joinedNS]);\n useEffect(() => {\n if (isMounted.current && ready) {\n setT(getT);\n }\n }, [i18n, keyPrefix, ready]);\n const ret = [t, i18n, ready];\n ret.t = t;\n ret.i18n = i18n;\n ret.ready = ready;\n if (ready) return ret;\n if (!ready && !useSuspense) return ret;\n throw new Promise(resolve => {\n if (props.lng) {\n loadLanguages(i18n, props.lng, namespaces, () => resolve());\n } else {\n loadNamespaces(i18n, namespaces, () => resolve());\n }\n });\n};","import { createElement, useMemo } from 'react';\nimport { I18nContext } from './context.js';\nexport function I18nextProvider({\n i18n,\n defaultNS,\n children\n}) {\n const value = useMemo(() => ({\n i18n,\n defaultNS\n }), [i18n, defaultNS]);\n return createElement(I18nContext.Provider, {\n value\n }, children);\n}","import { useContext } from 'react';\nimport { getI18n, I18nContext } from './context.js';\nexport const useSSR = (initialI18nStore, initialLanguage, props = {}) => {\n const {\n i18n: i18nFromProps\n } = props;\n const {\n i18n: i18nFromContext\n } = useContext(I18nContext) || {};\n const i18n = i18nFromProps || i18nFromContext || getI18n();\n if (i18n.options?.isClone) return;\n if (initialI18nStore && !i18n.initializedStoreOnce) {\n i18n.services.resourceStore.data = initialI18nStore;\n i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => {\n Object.keys(lngResources).forEach(ns => {\n if (mem.indexOf(ns) < 0) mem.push(ns);\n });\n return mem;\n }, i18n.options.ns);\n i18n.initializedStoreOnce = true;\n i18n.isInitialized = true;\n }\n if (initialLanguage && !i18n.initializedLanguageOnce) {\n i18n.changeLanguage(initialLanguage);\n i18n.initializedLanguageOnce = true;\n }\n};","import { Block } from '@mui/icons-material';\nimport { Box, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nexport const NotFound: React.FC = () => {\n const { t } = useTranslation();\n return (\n \n \n \n \n \n {t('tooltip.notFound.title')}\n \n \n {t('tooltip.notFound.text')}\n \n
\n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM8 9h8v10H8zm7.5-5-1-1h-5l-1 1H5v2h14V4z\"\n}), 'DeleteOutline');","'use client';\n\nimport * as React from 'react';\nimport { useTheme as useThemeSystem } from '@mui/system';\nimport defaultTheme from './defaultTheme';\nimport THEME_ID from './identifier';\nexport default function useTheme() {\n const theme = useThemeSystem(defaultTheme);\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n return theme[THEME_ID] || theme;\n}","/**\n * TODO v5: consider making it private\n *\n * passes {value} to {ref}\n *\n * WARNING: Be sure to only call this inside a callback that is passed as a ref.\n * Otherwise, make sure to cleanup the previous {ref} if it changes. See\n * https://github.com/mui/material-ui/issues/13539\n *\n * Useful if you want to expose the ref of an inner component to the public API\n * while still using it inside the component.\n * @param ref A ref callback or ref object. If anything falsy, this is a no-op.\n */\nexport default function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}","'use client';\n\nimport * as React from 'react';\nimport setRef from '../setRef';\nexport default function useForkRef(...refs) {\n /**\n * This will create a new function if the refs passed to this hook change and are all defined.\n * This means react will call the old forkRef with `null` and the new forkRef\n * with the ref. Cleanup naturally emerges from this behavior.\n */\n return React.useMemo(() => {\n if (refs.every(ref => ref == null)) {\n return null;\n }\n return instance => {\n refs.forEach(ref => {\n setRef(ref, instance);\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n}","'use client';\n\nimport useForkRef from '@mui/utils/useForkRef';\nexport default useForkRef;","'use client';\n\nimport * as React from 'react';\n\n/**\n * A version of `React.useLayoutEffect` that does not show a warning when server-side rendering.\n * This is useful for effects that are only needed for client-side rendering but not for SSR.\n *\n * Before you use this hook, make sure to read https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85\n * and confirm it doesn't apply to your use-case.\n */\nconst useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\nexport default useEnhancedEffect;","'use client';\n\nimport * as React from 'react';\nimport useEnhancedEffect from '../useEnhancedEffect';\n\n/**\n * Inspired by https://github.com/facebook/react/issues/14099#issuecomment-440013892\n * See RFC in https://github.com/reactjs/rfcs/pull/220\n */\n\nfunction useEventCallback(fn) {\n const ref = React.useRef(fn);\n useEnhancedEffect(() => {\n ref.current = fn;\n });\n return React.useRef((...args) =>\n // @ts-expect-error hide `this`\n (0, ref.current)(...args)).current;\n}\nexport default useEventCallback;","'use client';\n\nimport useEventCallback from '@mui/utils/useEventCallback';\nexport default useEventCallback;","'use client';\n\nimport * as React from 'react';\nconst UNINITIALIZED = {};\n\n/**\n * A React.useRef() that is initialized lazily with a function. Note that it accepts an optional\n * initialization argument, so the initialization function doesn't need to be an inline closure.\n *\n * @usage\n * const ref = useLazyRef(sortColumns, columns)\n */\nexport default function useLazyRef(init, initArg) {\n const ref = React.useRef(UNINITIALIZED);\n if (ref.current === UNINITIALIZED) {\n ref.current = init(initArg);\n }\n return ref;\n}","'use client';\n\nimport * as React from 'react';\nconst EMPTY = [];\n\n/**\n * A React.useEffect equivalent that runs once, when the component is mounted.\n */\nexport default function useOnMount(fn) {\n /* eslint-disable react-hooks/exhaustive-deps */\n React.useEffect(fn, EMPTY);\n /* eslint-enable react-hooks/exhaustive-deps */\n}","'use client';\n\nimport useLazyRef from '../useLazyRef/useLazyRef';\nimport useOnMount from '../useOnMount/useOnMount';\nexport class Timeout {\n constructor() {\n this.currentId = null;\n this.clear = () => {\n if (this.currentId !== null) {\n clearTimeout(this.currentId);\n this.currentId = null;\n }\n };\n this.disposeEffect = () => {\n return this.clear;\n };\n }\n static create() {\n return new Timeout();\n }\n /**\n * Executes `fn` after `delay`, clearing any previously scheduled call.\n */\n start(delay, fn) {\n this.clear();\n this.currentId = setTimeout(() => {\n this.currentId = null;\n fn();\n }, delay);\n }\n}\nexport default function useTimeout() {\n const timeout = useLazyRef(Timeout.create).current;\n useOnMount(timeout.disposeEffect);\n return timeout;\n}","'use client';\n\n// based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js\nimport * as React from 'react';\nimport { Timeout } from '../useTimeout/useTimeout';\nlet hadKeyboardEvent = true;\nlet hadFocusVisibleRecently = false;\nconst hadFocusVisibleRecentlyTimeout = new Timeout();\nconst inputTypesWhitelist = {\n text: true,\n search: true,\n url: true,\n tel: true,\n email: true,\n password: true,\n number: true,\n date: true,\n month: true,\n week: true,\n time: true,\n datetime: true,\n 'datetime-local': true\n};\n\n/**\n * Computes whether the given element should automatically trigger the\n * `focus-visible` class being added, i.e. whether it should always match\n * `:focus-visible` when focused.\n * @param {Element} node\n * @returns {boolean}\n */\nfunction focusTriggersKeyboardModality(node) {\n const {\n type,\n tagName\n } = node;\n if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) {\n return true;\n }\n if (tagName === 'TEXTAREA' && !node.readOnly) {\n return true;\n }\n if (node.isContentEditable) {\n return true;\n }\n return false;\n}\n\n/**\n * Keep track of our keyboard modality state with `hadKeyboardEvent`.\n * If the most recent user interaction was via the keyboard;\n * and the key press did not include a meta, alt/option, or control key;\n * then the modality is keyboard. Otherwise, the modality is not keyboard.\n * @param {KeyboardEvent} event\n */\nfunction handleKeyDown(event) {\n if (event.metaKey || event.altKey || event.ctrlKey) {\n return;\n }\n hadKeyboardEvent = true;\n}\n\n/**\n * If at any point a user clicks with a pointing device, ensure that we change\n * the modality away from keyboard.\n * This avoids the situation where a user presses a key on an already focused\n * element, and then clicks on a different element, focusing it with a\n * pointing device, while we still think we're in keyboard modality.\n */\nfunction handlePointerDown() {\n hadKeyboardEvent = false;\n}\nfunction handleVisibilityChange() {\n if (this.visibilityState === 'hidden') {\n // If the tab becomes active again, the browser will handle calling focus\n // on the element (Safari actually calls it twice).\n // If this tab change caused a blur on an element with focus-visible,\n // re-apply the class when the user switches back to the tab.\n if (hadFocusVisibleRecently) {\n hadKeyboardEvent = true;\n }\n }\n}\nfunction prepare(doc) {\n doc.addEventListener('keydown', handleKeyDown, true);\n doc.addEventListener('mousedown', handlePointerDown, true);\n doc.addEventListener('pointerdown', handlePointerDown, true);\n doc.addEventListener('touchstart', handlePointerDown, true);\n doc.addEventListener('visibilitychange', handleVisibilityChange, true);\n}\nexport function teardown(doc) {\n doc.removeEventListener('keydown', handleKeyDown, true);\n doc.removeEventListener('mousedown', handlePointerDown, true);\n doc.removeEventListener('pointerdown', handlePointerDown, true);\n doc.removeEventListener('touchstart', handlePointerDown, true);\n doc.removeEventListener('visibilitychange', handleVisibilityChange, true);\n}\nfunction isFocusVisible(event) {\n const {\n target\n } = event;\n try {\n return target.matches(':focus-visible');\n } catch (error) {\n // Browsers not implementing :focus-visible will throw a SyntaxError.\n // We use our own heuristic for those browsers.\n // Rethrow might be better if it's not the expected error but do we really\n // want to crash if focus-visible malfunctioned?\n }\n\n // No need for validFocusTarget check. The user does that by attaching it to\n // focusable events only.\n return hadKeyboardEvent || focusTriggersKeyboardModality(target);\n}\nexport default function useIsFocusVisible() {\n const ref = React.useCallback(node => {\n if (node != null) {\n prepare(node.ownerDocument);\n }\n }, []);\n const isFocusVisibleRef = React.useRef(false);\n\n /**\n * Should be called if a blur event is fired\n */\n function handleBlurVisible() {\n // checking against potential state variable does not suffice if we focus and blur synchronously.\n // React wouldn't have time to trigger a re-render so `focusVisible` would be stale.\n // Ideally we would adjust `isFocusVisible(event)` to look at `relatedTarget` for blur events.\n // This doesn't work in IE11 due to https://github.com/facebook/react/issues/3751\n // TODO: check again if React releases their internal changes to focus event handling (https://github.com/facebook/react/pull/19186).\n if (isFocusVisibleRef.current) {\n // To detect a tab/window switch, we look for a blur event followed\n // rapidly by a visibility change.\n // If we don't see a visibility change within 100ms, it's probably a\n // regular focus change.\n hadFocusVisibleRecently = true;\n hadFocusVisibleRecentlyTimeout.start(100, () => {\n hadFocusVisibleRecently = false;\n });\n isFocusVisibleRef.current = false;\n return true;\n }\n return false;\n }\n\n /**\n * Should be called if a blur event is fired\n */\n function handleFocusVisible(event) {\n if (isFocusVisible(event)) {\n isFocusVisibleRef.current = true;\n return true;\n }\n return false;\n }\n return {\n isFocusVisibleRef,\n onFocus: handleFocusVisible,\n onBlur: handleBlurVisible,\n ref\n };\n}","'use client';\n\nimport useIsFocusVisible from '@mui/utils/useIsFocusVisible';\nexport default useIsFocusVisible;","function _setPrototypeOf(t, e) {\n return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {\n return t.__proto__ = e, t;\n }, _setPrototypeOf(t, e);\n}\nexport { _setPrototypeOf as default };","import setPrototypeOf from \"./setPrototypeOf.js\";\nfunction _inheritsLoose(t, o) {\n t.prototype = Object.create(o.prototype), t.prototype.constructor = t, setPrototypeOf(t, o);\n}\nexport { _inheritsLoose as default };","import React from 'react';\nexport default React.createContext(null);","import { Children, cloneElement, isValidElement } from 'react';\n/**\n * Given `this.props.children`, return an object mapping key to child.\n *\n * @param {*} children `this.props.children`\n * @return {object} Mapping of key to child\n */\n\nexport function getChildMapping(children, mapFn) {\n var mapper = function mapper(child) {\n return mapFn && isValidElement(child) ? mapFn(child) : child;\n };\n\n var result = Object.create(null);\n if (children) Children.map(children, function (c) {\n return c;\n }).forEach(function (child) {\n // run the map function here instead so that the key is the computed one\n result[child.key] = mapper(child);\n });\n return result;\n}\n/**\n * When you're adding or removing children some may be added or removed in the\n * same render pass. We want to show *both* since we want to simultaneously\n * animate elements in and out. This function takes a previous set of keys\n * and a new set of keys and merges them with its best guess of the correct\n * ordering. In the future we may expose some of the utilities in\n * ReactMultiChild to make this easy, but for now React itself does not\n * directly have this concept of the union of prevChildren and nextChildren\n * so we implement it here.\n *\n * @param {object} prev prev children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @param {object} next next children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @return {object} a key set that contains all keys in `prev` and all keys\n * in `next` in a reasonable order.\n */\n\nexport function mergeChildMappings(prev, next) {\n prev = prev || {};\n next = next || {};\n\n function getValueForKey(key) {\n return key in next ? next[key] : prev[key];\n } // For each key of `next`, the list of keys to insert before that key in\n // the combined list\n\n\n var nextKeysPending = Object.create(null);\n var pendingKeys = [];\n\n for (var prevKey in prev) {\n if (prevKey in next) {\n if (pendingKeys.length) {\n nextKeysPending[prevKey] = pendingKeys;\n pendingKeys = [];\n }\n } else {\n pendingKeys.push(prevKey);\n }\n }\n\n var i;\n var childMapping = {};\n\n for (var nextKey in next) {\n if (nextKeysPending[nextKey]) {\n for (i = 0; i < nextKeysPending[nextKey].length; i++) {\n var pendingNextKey = nextKeysPending[nextKey][i];\n childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);\n }\n }\n\n childMapping[nextKey] = getValueForKey(nextKey);\n } // Finally, add the keys which didn't appear before any key in `next`\n\n\n for (i = 0; i < pendingKeys.length; i++) {\n childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);\n }\n\n return childMapping;\n}\n\nfunction getProp(child, prop, props) {\n return props[prop] != null ? props[prop] : child.props[prop];\n}\n\nexport function getInitialChildMapping(props, onExited) {\n return getChildMapping(props.children, function (child) {\n return cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n appear: getProp(child, 'appear', props),\n enter: getProp(child, 'enter', props),\n exit: getProp(child, 'exit', props)\n });\n });\n}\nexport function getNextChildMapping(nextProps, prevChildMapping, onExited) {\n var nextChildMapping = getChildMapping(nextProps.children);\n var children = mergeChildMappings(prevChildMapping, nextChildMapping);\n Object.keys(children).forEach(function (key) {\n var child = children[key];\n if (!isValidElement(child)) return;\n var hasPrev = (key in prevChildMapping);\n var hasNext = (key in nextChildMapping);\n var prevChild = prevChildMapping[key];\n var isLeaving = isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)\n\n if (hasNext && (!hasPrev || isLeaving)) {\n // console.log('entering', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n } else if (!hasNext && hasPrev && !isLeaving) {\n // item is old (exiting)\n // console.log('leaving', key)\n children[key] = cloneElement(child, {\n in: false\n });\n } else if (hasNext && hasPrev && isValidElement(prevChild)) {\n // item hasn't changed transition states\n // copy over the last transition props;\n // console.log('unchanged', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: prevChild.props.in,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n }\n });\n return children;\n}","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport TransitionGroupContext from './TransitionGroupContext';\nimport { getChildMapping, getInitialChildMapping, getNextChildMapping } from './utils/ChildMapping';\n\nvar values = Object.values || function (obj) {\n return Object.keys(obj).map(function (k) {\n return obj[k];\n });\n};\n\nvar defaultProps = {\n component: 'div',\n childFactory: function childFactory(child) {\n return child;\n }\n};\n/**\n * The `` component manages a set of transition components\n * (`` and ``) in a list. Like with the transition\n * components, `` is a state machine for managing the mounting\n * and unmounting of components over time.\n *\n * Consider the example below. As items are removed or added to the TodoList the\n * `in` prop is toggled automatically by the ``.\n *\n * Note that `` does not define any animation behavior!\n * Exactly _how_ a list item animates is up to the individual transition\n * component. This means you can mix and match animations across different list\n * items.\n */\n\nvar TransitionGroup = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(TransitionGroup, _React$Component);\n\n function TransitionGroup(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n\n var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear\n\n\n _this.state = {\n contextValue: {\n isMounting: true\n },\n handleExited: handleExited,\n firstRender: true\n };\n return _this;\n }\n\n var _proto = TransitionGroup.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.mounted = true;\n this.setState({\n contextValue: {\n isMounting: false\n }\n });\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.mounted = false;\n };\n\n TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {\n var prevChildMapping = _ref.children,\n handleExited = _ref.handleExited,\n firstRender = _ref.firstRender;\n return {\n children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),\n firstRender: false\n };\n } // node is `undefined` when user provided `nodeRef` prop\n ;\n\n _proto.handleExited = function handleExited(child, node) {\n var currentChildMapping = getChildMapping(this.props.children);\n if (child.key in currentChildMapping) return;\n\n if (child.props.onExited) {\n child.props.onExited(node);\n }\n\n if (this.mounted) {\n this.setState(function (state) {\n var children = _extends({}, state.children);\n\n delete children[child.key];\n return {\n children: children\n };\n });\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n Component = _this$props.component,\n childFactory = _this$props.childFactory,\n props = _objectWithoutPropertiesLoose(_this$props, [\"component\", \"childFactory\"]);\n\n var contextValue = this.state.contextValue;\n var children = values(this.state.children).map(childFactory);\n delete props.appear;\n delete props.enter;\n delete props.exit;\n\n if (Component === null) {\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, children);\n }\n\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, /*#__PURE__*/React.createElement(Component, props, children));\n };\n\n return TransitionGroup;\n}(React.Component);\n\nTransitionGroup.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * `` renders a `
` by default. You can change this\n * behavior by providing a `component` prop.\n * If you use React v16+ and would like to avoid a wrapping `
` element\n * you can pass in `component={null}`. This is useful if the wrapping div\n * borks your css styles.\n */\n component: PropTypes.any,\n\n /**\n * A set of `` components, that are toggled `in` and out as they\n * leave. the `` will inject specific transition props, so\n * remember to spread them through if you are wrapping the `` as\n * with our `` example.\n *\n * While this component is meant for multiple `Transition` or `CSSTransition`\n * children, sometimes you may want to have a single transition child with\n * content that you want to be transitioned out and in when you change it\n * (e.g. routes, images etc.) In that case you can change the `key` prop of\n * the transition child as you change its content, this will cause\n * `TransitionGroup` to transition the child out and back in.\n */\n children: PropTypes.node,\n\n /**\n * A convenience prop that enables or disables appear animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n appear: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables enter animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables exit animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * You may need to apply reactive updates to a child as it is exiting.\n * This is generally done by using `cloneElement` however in the case of an exiting\n * child the element has already been removed and not accessible to the consumer.\n *\n * If you do need to update a child as it leaves you can provide a `childFactory`\n * to wrap every child, even the ones that are leaving.\n *\n * @type Function(child: ReactElement) -> ReactElement\n */\n childFactory: PropTypes.func\n} : {};\nTransitionGroup.defaultProps = defaultProps;\nexport default TransitionGroup;","function _assertThisInitialized(e) {\n if (void 0 === e) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n return e;\n}\nexport { _assertThisInitialized as default };","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction Ripple(props) {\n const {\n className,\n classes,\n pulsate = false,\n rippleX,\n rippleY,\n rippleSize,\n in: inProp,\n onExited,\n timeout\n } = props;\n const [leaving, setLeaving] = React.useState(false);\n const rippleClassName = clsx(className, classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);\n const rippleStyles = {\n width: rippleSize,\n height: rippleSize,\n top: -(rippleSize / 2) + rippleY,\n left: -(rippleSize / 2) + rippleX\n };\n const childClassName = clsx(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);\n if (!inProp && !leaving) {\n setLeaving(true);\n }\n React.useEffect(() => {\n if (!inProp && onExited != null) {\n // react-transition-group#onExited\n const timeoutId = setTimeout(onExited, timeout);\n return () => {\n clearTimeout(timeoutId);\n };\n }\n return undefined;\n }, [onExited, inProp, timeout]);\n return /*#__PURE__*/_jsx(\"span\", {\n className: rippleClassName,\n style: rippleStyles,\n children: /*#__PURE__*/_jsx(\"span\", {\n className: childClassName\n })\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? Ripple.propTypes = {\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object.isRequired,\n className: PropTypes.string,\n /**\n * @ignore - injected from TransitionGroup\n */\n in: PropTypes.bool,\n /**\n * @ignore - injected from TransitionGroup\n */\n onExited: PropTypes.func,\n /**\n * If `true`, the ripple pulsates, typically indicating the keyboard focus state of an element.\n */\n pulsate: PropTypes.bool,\n /**\n * Diameter of the ripple.\n */\n rippleSize: PropTypes.number,\n /**\n * Horizontal position of the ripple center.\n */\n rippleX: PropTypes.number,\n /**\n * Vertical position of the ripple center.\n */\n rippleY: PropTypes.number,\n /**\n * exit delay\n */\n timeout: PropTypes.number.isRequired\n} : void 0;\nexport default Ripple;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getTouchRippleUtilityClass(slot) {\n return generateUtilityClass('MuiTouchRipple', slot);\n}\nconst touchRippleClasses = generateUtilityClasses('MuiTouchRipple', ['root', 'ripple', 'rippleVisible', 'ripplePulsate', 'child', 'childLeaving', 'childPulsate']);\nexport default touchRippleClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"center\", \"classes\", \"className\"];\nlet _ = t => t,\n _t,\n _t2,\n _t3,\n _t4;\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { TransitionGroup } from 'react-transition-group';\nimport clsx from 'clsx';\nimport { keyframes } from '@mui/system';\nimport useTimeout from '@mui/utils/useTimeout';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport Ripple from './Ripple';\nimport touchRippleClasses from './touchRippleClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst DURATION = 550;\nexport const DELAY_RIPPLE = 80;\nconst enterKeyframe = keyframes(_t || (_t = _`\n 0% {\n transform: scale(0);\n opacity: 0.1;\n }\n\n 100% {\n transform: scale(1);\n opacity: 0.3;\n }\n`));\nconst exitKeyframe = keyframes(_t2 || (_t2 = _`\n 0% {\n opacity: 1;\n }\n\n 100% {\n opacity: 0;\n }\n`));\nconst pulsateKeyframe = keyframes(_t3 || (_t3 = _`\n 0% {\n transform: scale(1);\n }\n\n 50% {\n transform: scale(0.92);\n }\n\n 100% {\n transform: scale(1);\n }\n`));\nexport const TouchRippleRoot = styled('span', {\n name: 'MuiTouchRipple',\n slot: 'Root'\n})({\n overflow: 'hidden',\n pointerEvents: 'none',\n position: 'absolute',\n zIndex: 0,\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n borderRadius: 'inherit'\n});\n\n// This `styled()` function invokes keyframes. `styled-components` only supports keyframes\n// in string templates. Do not convert these styles in JS object as it will break.\nexport const TouchRippleRipple = styled(Ripple, {\n name: 'MuiTouchRipple',\n slot: 'Ripple'\n})(_t4 || (_t4 = _`\n opacity: 0;\n position: absolute;\n\n &.${0} {\n opacity: 0.3;\n transform: scale(1);\n animation-name: ${0};\n animation-duration: ${0}ms;\n animation-timing-function: ${0};\n }\n\n &.${0} {\n animation-duration: ${0}ms;\n }\n\n & .${0} {\n opacity: 1;\n display: block;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n background-color: currentColor;\n }\n\n & .${0} {\n opacity: 0;\n animation-name: ${0};\n animation-duration: ${0}ms;\n animation-timing-function: ${0};\n }\n\n & .${0} {\n position: absolute;\n /* @noflip */\n left: 0px;\n top: 0;\n animation-name: ${0};\n animation-duration: 2500ms;\n animation-timing-function: ${0};\n animation-iteration-count: infinite;\n animation-delay: 200ms;\n }\n`), touchRippleClasses.rippleVisible, enterKeyframe, DURATION, ({\n theme\n}) => theme.transitions.easing.easeInOut, touchRippleClasses.ripplePulsate, ({\n theme\n}) => theme.transitions.duration.shorter, touchRippleClasses.child, touchRippleClasses.childLeaving, exitKeyframe, DURATION, ({\n theme\n}) => theme.transitions.easing.easeInOut, touchRippleClasses.childPulsate, pulsateKeyframe, ({\n theme\n}) => theme.transitions.easing.easeInOut);\n\n/**\n * @ignore - internal component.\n *\n * TODO v5: Make private\n */\nconst TouchRipple = /*#__PURE__*/React.forwardRef(function TouchRipple(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiTouchRipple'\n });\n const {\n center: centerProp = false,\n classes = {},\n className\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const [ripples, setRipples] = React.useState([]);\n const nextKey = React.useRef(0);\n const rippleCallback = React.useRef(null);\n React.useEffect(() => {\n if (rippleCallback.current) {\n rippleCallback.current();\n rippleCallback.current = null;\n }\n }, [ripples]);\n\n // Used to filter out mouse emulated events on mobile.\n const ignoringMouseDown = React.useRef(false);\n // We use a timer in order to only show the ripples for touch \"click\" like events.\n // We don't want to display the ripple for touch scroll events.\n const startTimer = useTimeout();\n\n // This is the hook called once the previous timeout is ready.\n const startTimerCommit = React.useRef(null);\n const container = React.useRef(null);\n const startCommit = React.useCallback(params => {\n const {\n pulsate,\n rippleX,\n rippleY,\n rippleSize,\n cb\n } = params;\n setRipples(oldRipples => [...oldRipples, /*#__PURE__*/_jsx(TouchRippleRipple, {\n classes: {\n ripple: clsx(classes.ripple, touchRippleClasses.ripple),\n rippleVisible: clsx(classes.rippleVisible, touchRippleClasses.rippleVisible),\n ripplePulsate: clsx(classes.ripplePulsate, touchRippleClasses.ripplePulsate),\n child: clsx(classes.child, touchRippleClasses.child),\n childLeaving: clsx(classes.childLeaving, touchRippleClasses.childLeaving),\n childPulsate: clsx(classes.childPulsate, touchRippleClasses.childPulsate)\n },\n timeout: DURATION,\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize\n }, nextKey.current)]);\n nextKey.current += 1;\n rippleCallback.current = cb;\n }, [classes]);\n const start = React.useCallback((event = {}, options = {}, cb = () => {}) => {\n const {\n pulsate = false,\n center = centerProp || options.pulsate,\n fakeElement = false // For test purposes\n } = options;\n if ((event == null ? void 0 : event.type) === 'mousedown' && ignoringMouseDown.current) {\n ignoringMouseDown.current = false;\n return;\n }\n if ((event == null ? void 0 : event.type) === 'touchstart') {\n ignoringMouseDown.current = true;\n }\n const element = fakeElement ? null : container.current;\n const rect = element ? element.getBoundingClientRect() : {\n width: 0,\n height: 0,\n left: 0,\n top: 0\n };\n\n // Get the size of the ripple\n let rippleX;\n let rippleY;\n let rippleSize;\n if (center || event === undefined || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {\n rippleX = Math.round(rect.width / 2);\n rippleY = Math.round(rect.height / 2);\n } else {\n const {\n clientX,\n clientY\n } = event.touches && event.touches.length > 0 ? event.touches[0] : event;\n rippleX = Math.round(clientX - rect.left);\n rippleY = Math.round(clientY - rect.top);\n }\n if (center) {\n rippleSize = Math.sqrt((2 * rect.width ** 2 + rect.height ** 2) / 3);\n\n // For some reason the animation is broken on Mobile Chrome if the size is even.\n if (rippleSize % 2 === 0) {\n rippleSize += 1;\n }\n } else {\n const sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;\n const sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;\n rippleSize = Math.sqrt(sizeX ** 2 + sizeY ** 2);\n }\n\n // Touche devices\n if (event != null && event.touches) {\n // check that this isn't another touchstart due to multitouch\n // otherwise we will only clear a single timer when unmounting while two\n // are running\n if (startTimerCommit.current === null) {\n // Prepare the ripple effect.\n startTimerCommit.current = () => {\n startCommit({\n pulsate,\n rippleX,\n rippleY,\n rippleSize,\n cb\n });\n };\n // Delay the execution of the ripple effect.\n // We have to make a tradeoff with this delay value.\n startTimer.start(DELAY_RIPPLE, () => {\n if (startTimerCommit.current) {\n startTimerCommit.current();\n startTimerCommit.current = null;\n }\n });\n }\n } else {\n startCommit({\n pulsate,\n rippleX,\n rippleY,\n rippleSize,\n cb\n });\n }\n }, [centerProp, startCommit, startTimer]);\n const pulsate = React.useCallback(() => {\n start({}, {\n pulsate: true\n });\n }, [start]);\n const stop = React.useCallback((event, cb) => {\n startTimer.clear();\n\n // The touch interaction occurs too quickly.\n // We still want to show ripple effect.\n if ((event == null ? void 0 : event.type) === 'touchend' && startTimerCommit.current) {\n startTimerCommit.current();\n startTimerCommit.current = null;\n startTimer.start(0, () => {\n stop(event, cb);\n });\n return;\n }\n startTimerCommit.current = null;\n setRipples(oldRipples => {\n if (oldRipples.length > 0) {\n return oldRipples.slice(1);\n }\n return oldRipples;\n });\n rippleCallback.current = cb;\n }, [startTimer]);\n React.useImperativeHandle(ref, () => ({\n pulsate,\n start,\n stop\n }), [pulsate, start, stop]);\n return /*#__PURE__*/_jsx(TouchRippleRoot, _extends({\n className: clsx(touchRippleClasses.root, classes.root, className),\n ref: container\n }, other, {\n children: /*#__PURE__*/_jsx(TransitionGroup, {\n component: null,\n exit: true,\n children: ripples\n })\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? TouchRipple.propTypes = {\n /**\n * If `true`, the ripple starts at the center of the component\n * rather than at the point of interaction.\n */\n center: PropTypes.bool,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string\n} : void 0;\nexport default TouchRipple;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getButtonBaseUtilityClass(slot) {\n return generateUtilityClass('MuiButtonBase', slot);\n}\nconst buttonBaseClasses = generateUtilityClasses('MuiButtonBase', ['root', 'disabled', 'focusVisible']);\nexport default buttonBaseClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"action\", \"centerRipple\", \"children\", \"className\", \"component\", \"disabled\", \"disableRipple\", \"disableTouchRipple\", \"focusRipple\", \"focusVisibleClassName\", \"LinkComponent\", \"onBlur\", \"onClick\", \"onContextMenu\", \"onDragLeave\", \"onFocus\", \"onFocusVisible\", \"onKeyDown\", \"onKeyUp\", \"onMouseDown\", \"onMouseLeave\", \"onMouseUp\", \"onTouchEnd\", \"onTouchMove\", \"onTouchStart\", \"tabIndex\", \"TouchRippleProps\", \"touchRippleRef\", \"type\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport refType from '@mui/utils/refType';\nimport elementTypeAcceptingRef from '@mui/utils/elementTypeAcceptingRef';\nimport composeClasses from '@mui/utils/composeClasses';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport useForkRef from '../utils/useForkRef';\nimport useEventCallback from '../utils/useEventCallback';\nimport useIsFocusVisible from '../utils/useIsFocusVisible';\nimport TouchRipple from './TouchRipple';\nimport buttonBaseClasses, { getButtonBaseUtilityClass } from './buttonBaseClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n disabled,\n focusVisible,\n focusVisibleClassName,\n classes\n } = ownerState;\n const slots = {\n root: ['root', disabled && 'disabled', focusVisible && 'focusVisible']\n };\n const composedClasses = composeClasses(slots, getButtonBaseUtilityClass, classes);\n if (focusVisible && focusVisibleClassName) {\n composedClasses.root += ` ${focusVisibleClassName}`;\n }\n return composedClasses;\n};\nexport const ButtonBaseRoot = styled('button', {\n name: 'MuiButtonBase',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n position: 'relative',\n boxSizing: 'border-box',\n WebkitTapHighlightColor: 'transparent',\n backgroundColor: 'transparent',\n // Reset default value\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n border: 0,\n margin: 0,\n // Remove the margin in Safari\n borderRadius: 0,\n padding: 0,\n // Remove the padding in Firefox\n cursor: 'pointer',\n userSelect: 'none',\n verticalAlign: 'middle',\n MozAppearance: 'none',\n // Reset\n WebkitAppearance: 'none',\n // Reset\n textDecoration: 'none',\n // So we take precedent over the style of a native element.\n color: 'inherit',\n '&::-moz-focus-inner': {\n borderStyle: 'none' // Remove Firefox dotted outline.\n },\n [`&.${buttonBaseClasses.disabled}`]: {\n pointerEvents: 'none',\n // Disable link interactions\n cursor: 'default'\n },\n '@media print': {\n colorAdjust: 'exact'\n }\n});\n\n/**\n * `ButtonBase` contains as few styles as possible.\n * It aims to be a simple building block for creating a button.\n * It contains a load of style reset and some focus/ripple logic.\n */\nconst ButtonBase = /*#__PURE__*/React.forwardRef(function ButtonBase(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiButtonBase'\n });\n const {\n action,\n centerRipple = false,\n children,\n className,\n component = 'button',\n disabled = false,\n disableRipple = false,\n disableTouchRipple = false,\n focusRipple = false,\n LinkComponent = 'a',\n onBlur,\n onClick,\n onContextMenu,\n onDragLeave,\n onFocus,\n onFocusVisible,\n onKeyDown,\n onKeyUp,\n onMouseDown,\n onMouseLeave,\n onMouseUp,\n onTouchEnd,\n onTouchMove,\n onTouchStart,\n tabIndex = 0,\n TouchRippleProps,\n touchRippleRef,\n type\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const buttonRef = React.useRef(null);\n const rippleRef = React.useRef(null);\n const handleRippleRef = useForkRef(rippleRef, touchRippleRef);\n const {\n isFocusVisibleRef,\n onFocus: handleFocusVisible,\n onBlur: handleBlurVisible,\n ref: focusVisibleRef\n } = useIsFocusVisible();\n const [focusVisible, setFocusVisible] = React.useState(false);\n if (disabled && focusVisible) {\n setFocusVisible(false);\n }\n React.useImperativeHandle(action, () => ({\n focusVisible: () => {\n setFocusVisible(true);\n buttonRef.current.focus();\n }\n }), []);\n const [mountedState, setMountedState] = React.useState(false);\n React.useEffect(() => {\n setMountedState(true);\n }, []);\n const enableTouchRipple = mountedState && !disableRipple && !disabled;\n React.useEffect(() => {\n if (focusVisible && focusRipple && !disableRipple && mountedState) {\n rippleRef.current.pulsate();\n }\n }, [disableRipple, focusRipple, focusVisible, mountedState]);\n function useRippleHandler(rippleAction, eventCallback, skipRippleAction = disableTouchRipple) {\n return useEventCallback(event => {\n if (eventCallback) {\n eventCallback(event);\n }\n const ignore = skipRippleAction;\n if (!ignore && rippleRef.current) {\n rippleRef.current[rippleAction](event);\n }\n return true;\n });\n }\n const handleMouseDown = useRippleHandler('start', onMouseDown);\n const handleContextMenu = useRippleHandler('stop', onContextMenu);\n const handleDragLeave = useRippleHandler('stop', onDragLeave);\n const handleMouseUp = useRippleHandler('stop', onMouseUp);\n const handleMouseLeave = useRippleHandler('stop', event => {\n if (focusVisible) {\n event.preventDefault();\n }\n if (onMouseLeave) {\n onMouseLeave(event);\n }\n });\n const handleTouchStart = useRippleHandler('start', onTouchStart);\n const handleTouchEnd = useRippleHandler('stop', onTouchEnd);\n const handleTouchMove = useRippleHandler('stop', onTouchMove);\n const handleBlur = useRippleHandler('stop', event => {\n handleBlurVisible(event);\n if (isFocusVisibleRef.current === false) {\n setFocusVisible(false);\n }\n if (onBlur) {\n onBlur(event);\n }\n }, false);\n const handleFocus = useEventCallback(event => {\n // Fix for https://github.com/facebook/react/issues/7769\n if (!buttonRef.current) {\n buttonRef.current = event.currentTarget;\n }\n handleFocusVisible(event);\n if (isFocusVisibleRef.current === true) {\n setFocusVisible(true);\n if (onFocusVisible) {\n onFocusVisible(event);\n }\n }\n if (onFocus) {\n onFocus(event);\n }\n });\n const isNonNativeButton = () => {\n const button = buttonRef.current;\n return component && component !== 'button' && !(button.tagName === 'A' && button.href);\n };\n\n /**\n * IE11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat\n */\n const keydownRef = React.useRef(false);\n const handleKeyDown = useEventCallback(event => {\n // Check if key is already down to avoid repeats being counted as multiple activations\n if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') {\n keydownRef.current = true;\n rippleRef.current.stop(event, () => {\n rippleRef.current.start(event);\n });\n }\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {\n event.preventDefault();\n }\n if (onKeyDown) {\n onKeyDown(event);\n }\n\n // Keyboard accessibility for non interactive elements\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) {\n event.preventDefault();\n if (onClick) {\n onClick(event);\n }\n }\n });\n const handleKeyUp = useEventCallback(event => {\n // calling preventDefault in keyUp on a \n *
\n * );\n * }\n * ```\n *\n * When the button is clicked the component will shift to the `'entering'` state\n * and stay there for 500ms (the value of `timeout`) before it finally switches\n * to `'entered'`.\n *\n * When `in` is `false` the same thing happens except the state moves from\n * `'exiting'` to `'exited'`.\n */\n\nvar Transition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Transition, _React$Component);\n\n function Transition(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n var parentGroup = context; // In the context of a TransitionGroup all enters are really appears\n\n var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;\n var initialStatus;\n _this.appearStatus = null;\n\n if (props.in) {\n if (appear) {\n initialStatus = EXITED;\n _this.appearStatus = ENTERING;\n } else {\n initialStatus = ENTERED;\n }\n } else {\n if (props.unmountOnExit || props.mountOnEnter) {\n initialStatus = UNMOUNTED;\n } else {\n initialStatus = EXITED;\n }\n }\n\n _this.state = {\n status: initialStatus\n };\n _this.nextCallback = null;\n return _this;\n }\n\n Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {\n var nextIn = _ref.in;\n\n if (nextIn && prevState.status === UNMOUNTED) {\n return {\n status: EXITED\n };\n }\n\n return null;\n } // getSnapshotBeforeUpdate(prevProps) {\n // let nextStatus = null\n // if (prevProps !== this.props) {\n // const { status } = this.state\n // if (this.props.in) {\n // if (status !== ENTERING && status !== ENTERED) {\n // nextStatus = ENTERING\n // }\n // } else {\n // if (status === ENTERING || status === ENTERED) {\n // nextStatus = EXITING\n // }\n // }\n // }\n // return { nextStatus }\n // }\n ;\n\n var _proto = Transition.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.updateStatus(true, this.appearStatus);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n var nextStatus = null;\n\n if (prevProps !== this.props) {\n var status = this.state.status;\n\n if (this.props.in) {\n if (status !== ENTERING && status !== ENTERED) {\n nextStatus = ENTERING;\n }\n } else {\n if (status === ENTERING || status === ENTERED) {\n nextStatus = EXITING;\n }\n }\n }\n\n this.updateStatus(false, nextStatus);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.cancelNextCallback();\n };\n\n _proto.getTimeouts = function getTimeouts() {\n var timeout = this.props.timeout;\n var exit, enter, appear;\n exit = enter = appear = timeout;\n\n if (timeout != null && typeof timeout !== 'number') {\n exit = timeout.exit;\n enter = timeout.enter; // TODO: remove fallback for next major\n\n appear = timeout.appear !== undefined ? timeout.appear : enter;\n }\n\n return {\n exit: exit,\n enter: enter,\n appear: appear\n };\n };\n\n _proto.updateStatus = function updateStatus(mounting, nextStatus) {\n if (mounting === void 0) {\n mounting = false;\n }\n\n if (nextStatus !== null) {\n // nextStatus will always be ENTERING or EXITING.\n this.cancelNextCallback();\n\n if (nextStatus === ENTERING) {\n if (this.props.unmountOnExit || this.props.mountOnEnter) {\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this); // https://github.com/reactjs/react-transition-group/pull/749\n // With unmountOnExit or mountOnEnter, the enter animation should happen at the transition between `exited` and `entering`.\n // To make the animation happen, we have to separate each rendering and avoid being processed as batched.\n\n if (node) forceReflow(node);\n }\n\n this.performEnter(mounting);\n } else {\n this.performExit();\n }\n } else if (this.props.unmountOnExit && this.state.status === EXITED) {\n this.setState({\n status: UNMOUNTED\n });\n }\n };\n\n _proto.performEnter = function performEnter(mounting) {\n var _this2 = this;\n\n var enter = this.props.enter;\n var appearing = this.context ? this.context.isMounting : mounting;\n\n var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],\n maybeNode = _ref2[0],\n maybeAppearing = _ref2[1];\n\n var timeouts = this.getTimeouts();\n var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED\n // if we are mounting and running this it means appear _must_ be set\n\n if (!mounting && !enter || config.disabled) {\n this.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode);\n });\n return;\n }\n\n this.props.onEnter(maybeNode, maybeAppearing);\n this.safeSetState({\n status: ENTERING\n }, function () {\n _this2.props.onEntering(maybeNode, maybeAppearing);\n\n _this2.onTransitionEnd(enterTimeout, function () {\n _this2.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode, maybeAppearing);\n });\n });\n });\n };\n\n _proto.performExit = function performExit() {\n var _this3 = this;\n\n var exit = this.props.exit;\n var timeouts = this.getTimeouts();\n var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED\n\n if (!exit || config.disabled) {\n this.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n return;\n }\n\n this.props.onExit(maybeNode);\n this.safeSetState({\n status: EXITING\n }, function () {\n _this3.props.onExiting(maybeNode);\n\n _this3.onTransitionEnd(timeouts.exit, function () {\n _this3.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n });\n });\n };\n\n _proto.cancelNextCallback = function cancelNextCallback() {\n if (this.nextCallback !== null) {\n this.nextCallback.cancel();\n this.nextCallback = null;\n }\n };\n\n _proto.safeSetState = function safeSetState(nextState, callback) {\n // This shouldn't be necessary, but there are weird race conditions with\n // setState callbacks and unmounting in testing, so always make sure that\n // we can cancel any pending setState callbacks after we unmount.\n callback = this.setNextCallback(callback);\n this.setState(nextState, callback);\n };\n\n _proto.setNextCallback = function setNextCallback(callback) {\n var _this4 = this;\n\n var active = true;\n\n this.nextCallback = function (event) {\n if (active) {\n active = false;\n _this4.nextCallback = null;\n callback(event);\n }\n };\n\n this.nextCallback.cancel = function () {\n active = false;\n };\n\n return this.nextCallback;\n };\n\n _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {\n this.setNextCallback(handler);\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);\n var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;\n\n if (!node || doesNotHaveTimeoutOrListener) {\n setTimeout(this.nextCallback, 0);\n return;\n }\n\n if (this.props.addEndListener) {\n var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],\n maybeNode = _ref3[0],\n maybeNextCallback = _ref3[1];\n\n this.props.addEndListener(maybeNode, maybeNextCallback);\n }\n\n if (timeout != null) {\n setTimeout(this.nextCallback, timeout);\n }\n };\n\n _proto.render = function render() {\n var status = this.state.status;\n\n if (status === UNMOUNTED) {\n return null;\n }\n\n var _this$props = this.props,\n children = _this$props.children,\n _in = _this$props.in,\n _mountOnEnter = _this$props.mountOnEnter,\n _unmountOnExit = _this$props.unmountOnExit,\n _appear = _this$props.appear,\n _enter = _this$props.enter,\n _exit = _this$props.exit,\n _timeout = _this$props.timeout,\n _addEndListener = _this$props.addEndListener,\n _onEnter = _this$props.onEnter,\n _onEntering = _this$props.onEntering,\n _onEntered = _this$props.onEntered,\n _onExit = _this$props.onExit,\n _onExiting = _this$props.onExiting,\n _onExited = _this$props.onExited,\n _nodeRef = _this$props.nodeRef,\n childProps = _objectWithoutPropertiesLoose(_this$props, [\"children\", \"in\", \"mountOnEnter\", \"unmountOnExit\", \"appear\", \"enter\", \"exit\", \"timeout\", \"addEndListener\", \"onEnter\", \"onEntering\", \"onEntered\", \"onExit\", \"onExiting\", \"onExited\", \"nodeRef\"]);\n\n return (\n /*#__PURE__*/\n // allows for nested Transitions\n React.createElement(TransitionGroupContext.Provider, {\n value: null\n }, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))\n );\n };\n\n return Transition;\n}(React.Component);\n\nTransition.contextType = TransitionGroupContext;\nTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * A React reference to DOM element that need to transition:\n * https://stackoverflow.com/a/51127130/4671932\n *\n * - When `nodeRef` prop is used, `node` is not passed to callback functions\n * (e.g. `onEnter`) because user already has direct access to the node.\n * - When changing `key` prop of `Transition` in a `TransitionGroup` a new\n * `nodeRef` need to be provided to `Transition` with changed `key` prop\n * (see\n * [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).\n */\n nodeRef: PropTypes.shape({\n current: typeof Element === 'undefined' ? PropTypes.any : function (propValue, key, componentName, location, propFullName, secret) {\n var value = propValue[key];\n return PropTypes.instanceOf(value && 'ownerDocument' in value ? value.ownerDocument.defaultView.Element : Element)(propValue, key, componentName, location, propFullName, secret);\n }\n }),\n\n /**\n * A `function` child can be used instead of a React element. This function is\n * called with the current transition status (`'entering'`, `'entered'`,\n * `'exiting'`, `'exited'`), which can be used to apply context\n * specific props to a component.\n *\n * ```jsx\n * \n * {state => (\n * \n * )}\n * \n * ```\n */\n children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,\n\n /**\n * Show the component; triggers the enter or exit states\n */\n in: PropTypes.bool,\n\n /**\n * By default the child component is mounted immediately along with\n * the parent `Transition` component. If you want to \"lazy mount\" the component on the\n * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay\n * mounted, even on \"exited\", unless you also specify `unmountOnExit`.\n */\n mountOnEnter: PropTypes.bool,\n\n /**\n * By default the child component stays mounted after it reaches the `'exited'` state.\n * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.\n */\n unmountOnExit: PropTypes.bool,\n\n /**\n * By default the child component does not perform the enter transition when\n * it first mounts, regardless of the value of `in`. If you want this\n * behavior, set both `appear` and `in` to `true`.\n *\n * > **Note**: there are no special appear states like `appearing`/`appeared`, this prop\n * > only adds an additional enter transition. However, in the\n * > `` component that first enter transition does result in\n * > additional `.appear-*` classes, that way you can choose to style it\n * > differently.\n */\n appear: PropTypes.bool,\n\n /**\n * Enable or disable enter transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * Enable or disable exit transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * The duration of the transition, in milliseconds.\n * Required unless `addEndListener` is provided.\n *\n * You may specify a single timeout for all transitions:\n *\n * ```jsx\n * timeout={500}\n * ```\n *\n * or individually:\n *\n * ```jsx\n * timeout={{\n * appear: 500,\n * enter: 300,\n * exit: 500,\n * }}\n * ```\n *\n * - `appear` defaults to the value of `enter`\n * - `enter` defaults to `0`\n * - `exit` defaults to `0`\n *\n * @type {number | { enter?: number, exit?: number, appear?: number }}\n */\n timeout: function timeout(props) {\n var pt = timeoutsShape;\n if (!props.addEndListener) pt = pt.isRequired;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return pt.apply(void 0, [props].concat(args));\n },\n\n /**\n * Add a custom transition end trigger. Called with the transitioning\n * DOM node and a `done` callback. Allows for more fine grained transition end\n * logic. Timeouts are still used as a fallback if provided.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * ```jsx\n * addEndListener={(node, done) => {\n * // use the css transitionend event to mark the finish of a transition\n * node.addEventListener('transitionend', done, false);\n * }}\n * ```\n */\n addEndListener: PropTypes.func,\n\n /**\n * Callback fired before the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired after the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired after the \"entered\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired before the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired after the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExiting: PropTypes.func,\n\n /**\n * Callback fired after the \"exited\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExited: PropTypes.func\n} : {}; // Name the function so it is clearer in the documentation\n\nfunction noop() {}\n\nTransition.defaultProps = {\n in: false,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n enter: true,\n exit: true,\n onEnter: noop,\n onEntering: noop,\n onEntered: noop,\n onExit: noop,\n onExiting: noop,\n onExited: noop\n};\nTransition.UNMOUNTED = UNMOUNTED;\nTransition.EXITED = EXITED;\nTransition.ENTERING = ENTERING;\nTransition.ENTERED = ENTERED;\nTransition.EXITING = EXITING;\nexport default Transition;","export const reflow = node => node.scrollTop;\nexport function getTransitionProps(props, options) {\n var _style$transitionDura, _style$transitionTimi;\n const {\n timeout,\n easing,\n style = {}\n } = props;\n return {\n duration: (_style$transitionDura = style.transitionDuration) != null ? _style$transitionDura : typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,\n easing: (_style$transitionTimi = style.transitionTimingFunction) != null ? _style$transitionTimi : typeof easing === 'object' ? easing[options.mode] : easing,\n delay: style.transitionDelay\n };\n}","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"addEndListener\", \"appear\", \"children\", \"easing\", \"in\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"style\", \"timeout\", \"TransitionComponent\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport useTimeout from '@mui/utils/useTimeout';\nimport elementAcceptingRef from '@mui/utils/elementAcceptingRef';\nimport { Transition } from 'react-transition-group';\nimport useTheme from '../styles/useTheme';\nimport { getTransitionProps, reflow } from '../transitions/utils';\nimport useForkRef from '../utils/useForkRef';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction getScale(value) {\n return `scale(${value}, ${value ** 2})`;\n}\nconst styles = {\n entering: {\n opacity: 1,\n transform: getScale(1)\n },\n entered: {\n opacity: 1,\n transform: 'none'\n }\n};\n\n/*\n TODO v6: remove\n Conditionally apply a workaround for the CSS transition bug in Safari 15.4 / WebKit browsers.\n */\nconst isWebKit154 = typeof navigator !== 'undefined' && /^((?!chrome|android).)*(safari|mobile)/i.test(navigator.userAgent) && /(os |version\\/)15(.|_)4/i.test(navigator.userAgent);\n\n/**\n * The Grow transition is used by the [Tooltip](/material-ui/react-tooltip/) and\n * [Popover](/material-ui/react-popover/) components.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\nconst Grow = /*#__PURE__*/React.forwardRef(function Grow(props, ref) {\n const {\n addEndListener,\n appear = true,\n children,\n easing,\n in: inProp,\n onEnter,\n onEntered,\n onEntering,\n onExit,\n onExited,\n onExiting,\n style,\n timeout = 'auto',\n // eslint-disable-next-line react/prop-types\n TransitionComponent = Transition\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const timer = useTimeout();\n const autoTimeout = React.useRef();\n const theme = useTheme();\n const nodeRef = React.useRef(null);\n const handleRef = useForkRef(nodeRef, children.ref, ref);\n const normalizedTransitionCallback = callback => maybeIsAppearing => {\n if (callback) {\n const node = nodeRef.current;\n\n // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n if (maybeIsAppearing === undefined) {\n callback(node);\n } else {\n callback(node, maybeIsAppearing);\n }\n }\n };\n const handleEntering = normalizedTransitionCallback(onEntering);\n const handleEnter = normalizedTransitionCallback((node, isAppearing) => {\n reflow(node); // So the animation always start from the start.\n\n const {\n duration: transitionDuration,\n delay,\n easing: transitionTimingFunction\n } = getTransitionProps({\n style,\n timeout,\n easing\n }, {\n mode: 'enter'\n });\n let duration;\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n node.style.transition = [theme.transitions.create('opacity', {\n duration,\n delay\n }), theme.transitions.create('transform', {\n duration: isWebKit154 ? duration : duration * 0.666,\n delay,\n easing: transitionTimingFunction\n })].join(',');\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n const handleEntered = normalizedTransitionCallback(onEntered);\n const handleExiting = normalizedTransitionCallback(onExiting);\n const handleExit = normalizedTransitionCallback(node => {\n const {\n duration: transitionDuration,\n delay,\n easing: transitionTimingFunction\n } = getTransitionProps({\n style,\n timeout,\n easing\n }, {\n mode: 'exit'\n });\n let duration;\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n node.style.transition = [theme.transitions.create('opacity', {\n duration,\n delay\n }), theme.transitions.create('transform', {\n duration: isWebKit154 ? duration : duration * 0.666,\n delay: isWebKit154 ? delay : delay || duration * 0.333,\n easing: transitionTimingFunction\n })].join(',');\n node.style.opacity = 0;\n node.style.transform = getScale(0.75);\n if (onExit) {\n onExit(node);\n }\n });\n const handleExited = normalizedTransitionCallback(onExited);\n const handleAddEndListener = next => {\n if (timeout === 'auto') {\n timer.start(autoTimeout.current || 0, next);\n }\n if (addEndListener) {\n // Old call signature before `react-transition-group` implemented `nodeRef`\n addEndListener(nodeRef.current, next);\n }\n };\n return /*#__PURE__*/_jsx(TransitionComponent, _extends({\n appear: appear,\n in: inProp,\n nodeRef: nodeRef,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: handleAddEndListener,\n timeout: timeout === 'auto' ? null : timeout\n }, other, {\n children: (state, childProps) => {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n style: _extends({\n opacity: 0,\n transform: getScale(0.75),\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined\n }, styles[state], style, children.props.style),\n ref: handleRef\n }, childProps));\n }\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Grow.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Add a custom transition end trigger. Called with the transitioning DOM\n * node and a done callback. Allows for more fine grained transition end\n * logic. Note: Timeouts are still used as a fallback if provided.\n */\n addEndListener: PropTypes.func,\n /**\n * Perform the enter transition when it first mounts if `in` is also `true`.\n * Set this to `false` to disable this behavior.\n * @default true\n */\n appear: PropTypes.bool,\n /**\n * A single child content element.\n */\n children: elementAcceptingRef.isRequired,\n /**\n * The transition timing function.\n * You may specify a single easing or a object containing enter and exit values.\n */\n easing: PropTypes.oneOfType([PropTypes.shape({\n enter: PropTypes.string,\n exit: PropTypes.string\n }), PropTypes.string]),\n /**\n * If `true`, the component will transition in.\n */\n in: PropTypes.bool,\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n *\n * Set to 'auto' to automatically calculate transition time based on height.\n * @default 'auto'\n */\n timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nGrow.muiSupportAuto = true;\nexport default Grow;","export default function ownerDocument(node) {\n return node && node.ownerDocument || document;\n}","export default function getWindow(node) {\n if (node == null) {\n return window;\n }\n\n if (node.toString() !== '[object Window]') {\n var ownerDocument = node.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView || window : window;\n }\n\n return node;\n}","import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n var OwnElement = getWindow(node).Element;\n return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n var OwnElement = getWindow(node).HTMLElement;\n return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n // IE 11 has no ShadowRoot\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n\n var OwnElement = getWindow(node).ShadowRoot;\n return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };","export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;","export default function getUAString() {\n var uaData = navigator.userAgentData;\n\n if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {\n return uaData.brands.map(function (item) {\n return item.brand + \"/\" + item.version;\n }).join(' ');\n }\n\n return navigator.userAgent;\n}","import getUAString from \"../utils/userAgent.js\";\nexport default function isLayoutViewport() {\n return !/^((?!chrome|android).)*safari/i.test(getUAString());\n}","import { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nimport getWindow from \"./getWindow.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getBoundingClientRect(element, includeScale, isFixedStrategy) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n\n var clientRect = element.getBoundingClientRect();\n var scaleX = 1;\n var scaleY = 1;\n\n if (includeScale && isHTMLElement(element)) {\n scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;\n scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;\n }\n\n var _ref = isElement(element) ? getWindow(element) : window,\n visualViewport = _ref.visualViewport;\n\n var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;\n var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;\n var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;\n var width = clientRect.width / scaleX;\n var height = clientRect.height / scaleY;\n return {\n width: width,\n height: height,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x,\n x: x,\n y: y\n };\n}","import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n var win = getWindow(node);\n var scrollLeft = win.pageXOffset;\n var scrollTop = win.pageYOffset;\n return {\n scrollLeft: scrollLeft,\n scrollTop: scrollTop\n };\n}","export default function getNodeName(element) {\n return element ? (element.nodeName || '').toLowerCase() : null;\n}","import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n element.document) || window.document).documentElement;\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n // Popper 1 is broken in this case and never had a bug report so let's assume\n // it's not an issue. I don't think anyone ever specifies width on \n // anyway.\n // Browsers where the left scrollbar doesn't cause an issue report `0` for\n // this (e.g. Edge 2019, IE11, Safari)\n return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}","import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}","import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n // Firefox wants us to check `-x` and `-y` variations as well\n var _getComputedStyle = getComputedStyle(element),\n overflow = _getComputedStyle.overflow,\n overflowX = _getComputedStyle.overflowX,\n overflowY = _getComputedStyle.overflowY;\n\n return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n var rect = element.getBoundingClientRect();\n var scaleX = round(rect.width) / element.offsetWidth || 1;\n var scaleY = round(rect.height) / element.offsetHeight || 1;\n return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n\n var isOffsetParentAnElement = isHTMLElement(offsetParent);\n var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n var documentElement = getDocumentElement(offsetParent);\n var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);\n var scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n var offsets = {\n x: 0,\n y: 0\n };\n\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n isScrollParent(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n\n if (isHTMLElement(offsetParent)) {\n offsets = getBoundingClientRect(offsetParent, true);\n offsets.x += offsetParent.clientLeft;\n offsets.y += offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}","import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n if (node === getWindow(node) || !isHTMLElement(node)) {\n return getWindowScroll(node);\n } else {\n return getHTMLElementScroll(node);\n }\n}","export default function getHTMLElementScroll(element) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n var width = element.offsetWidth;\n var height = element.offsetHeight;\n\n if (Math.abs(clientRect.width - width) <= 1) {\n width = clientRect.width;\n }\n\n if (Math.abs(clientRect.height - height) <= 1) {\n height = clientRect.height;\n }\n\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: width,\n height: height\n };\n}","import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n if (getNodeName(element) === 'html') {\n return element;\n }\n\n return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n // $FlowFixMe[incompatible-return]\n // $FlowFixMe[prop-missing]\n element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n element.parentNode || ( // DOM Element detected\n isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n getDocumentElement(element) // fallback\n\n );\n}","import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return node.ownerDocument.body;\n }\n\n if (isHTMLElement(node) && isScrollParent(node)) {\n return node;\n }\n\n return getScrollParent(getParentNode(node));\n}","import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n var _element$ownerDocumen;\n\n if (list === void 0) {\n list = [];\n }\n\n var scrollParent = getScrollParent(element);\n var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n var win = getWindow(scrollParent);\n var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n var updatedList = list.concat(target);\n return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n updatedList.concat(listScrollParents(getParentNode(target)));\n}","import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}","import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement, isShadowRoot } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getUAString from \"../utils/userAgent.js\";\n\nfunction getTrueOffsetParent(element) {\n if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n getComputedStyle(element).position === 'fixed') {\n return null;\n }\n\n return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n var isFirefox = /firefox/i.test(getUAString());\n var isIE = /Trident/i.test(getUAString());\n\n if (isIE && isHTMLElement(element)) {\n // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n var elementCss = getComputedStyle(element);\n\n if (elementCss.position === 'fixed') {\n return null;\n }\n }\n\n var currentNode = getParentNode(element);\n\n if (isShadowRoot(currentNode)) {\n currentNode = currentNode.host;\n }\n\n while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n // create a containing block.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {\n return currentNode;\n } else {\n currentNode = currentNode.parentNode;\n }\n }\n\n return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n var window = getWindow(element);\n var offsetParent = getTrueOffsetParent(element);\n\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent);\n }\n\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n return window;\n }\n\n return offsetParent || getContainingBlock(element) || window;\n}","export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];","import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n var map = new Map();\n var visited = new Set();\n var result = [];\n modifiers.forEach(function (modifier) {\n map.set(modifier.name, modifier);\n }); // On visiting object, check for its dependencies and visit them recursively\n\n function sort(modifier) {\n visited.add(modifier.name);\n var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n requires.forEach(function (dep) {\n if (!visited.has(dep)) {\n var depModifier = map.get(dep);\n\n if (depModifier) {\n sort(depModifier);\n }\n }\n });\n result.push(modifier);\n }\n\n modifiers.forEach(function (modifier) {\n if (!visited.has(modifier.name)) {\n // check for visited object\n sort(modifier);\n }\n });\n return result;\n}\n\nexport default function orderModifiers(modifiers) {\n // order based on dependencies\n var orderedModifiers = order(modifiers); // order based on phase\n\n return modifierPhases.reduce(function (acc, phase) {\n return acc.concat(orderedModifiers.filter(function (modifier) {\n return modifier.phase === phase;\n }));\n }, []);\n}","export default function debounce(fn) {\n var pending;\n return function () {\n if (!pending) {\n pending = new Promise(function (resolve) {\n Promise.resolve().then(function () {\n pending = undefined;\n resolve(fn());\n });\n });\n }\n\n return pending;\n };\n}","import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nvar DEFAULT_OPTIONS = {\n placement: 'bottom',\n modifiers: [],\n strategy: 'absolute'\n};\n\nfunction areValidElements() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return !args.some(function (element) {\n return !(element && typeof element.getBoundingClientRect === 'function');\n });\n}\n\nexport function popperGenerator(generatorOptions) {\n if (generatorOptions === void 0) {\n generatorOptions = {};\n }\n\n var _generatorOptions = generatorOptions,\n _generatorOptions$def = _generatorOptions.defaultModifiers,\n defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n _generatorOptions$def2 = _generatorOptions.defaultOptions,\n defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n return function createPopper(reference, popper, options) {\n if (options === void 0) {\n options = defaultOptions;\n }\n\n var state = {\n placement: 'bottom',\n orderedModifiers: [],\n options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n modifiersData: {},\n elements: {\n reference: reference,\n popper: popper\n },\n attributes: {},\n styles: {}\n };\n var effectCleanupFns = [];\n var isDestroyed = false;\n var instance = {\n state: state,\n setOptions: function setOptions(setOptionsAction) {\n var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n cleanupModifierEffects();\n state.options = Object.assign({}, defaultOptions, state.options, options);\n state.scrollParents = {\n reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n popper: listScrollParents(popper)\n }; // Orders the modifiers based on their dependencies and `phase`\n // properties\n\n var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n state.orderedModifiers = orderedModifiers.filter(function (m) {\n return m.enabled;\n });\n runModifierEffects();\n return instance.update();\n },\n // Sync update – it will always be executed, even if not necessary. This\n // is useful for low frequency updates where sync behavior simplifies the\n // logic.\n // For high frequency updates (e.g. `resize` and `scroll` events), always\n // prefer the async Popper#update method\n forceUpdate: function forceUpdate() {\n if (isDestroyed) {\n return;\n }\n\n var _state$elements = state.elements,\n reference = _state$elements.reference,\n popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n // anymore\n\n if (!areValidElements(reference, popper)) {\n return;\n } // Store the reference and popper rects to be read by modifiers\n\n\n state.rects = {\n reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n popper: getLayoutRect(popper)\n }; // Modifiers have the ability to reset the current update cycle. The\n // most common use case for this is the `flip` modifier changing the\n // placement, which then needs to re-run all the modifiers, because the\n // logic was previously ran for the previous placement and is therefore\n // stale/incorrect\n\n state.reset = false;\n state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n // is filled with the initial data specified by the modifier. This means\n // it doesn't persist and is fresh on each update.\n // To ensure persistent data, use `${name}#persistent`\n\n state.orderedModifiers.forEach(function (modifier) {\n return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n });\n\n for (var index = 0; index < state.orderedModifiers.length; index++) {\n if (state.reset === true) {\n state.reset = false;\n index = -1;\n continue;\n }\n\n var _state$orderedModifie = state.orderedModifiers[index],\n fn = _state$orderedModifie.fn,\n _state$orderedModifie2 = _state$orderedModifie.options,\n _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n name = _state$orderedModifie.name;\n\n if (typeof fn === 'function') {\n state = fn({\n state: state,\n options: _options,\n name: name,\n instance: instance\n }) || state;\n }\n }\n },\n // Async and optimistically optimized update – it will not be executed if\n // not necessary (debounced to run at most once-per-tick)\n update: debounce(function () {\n return new Promise(function (resolve) {\n instance.forceUpdate();\n resolve(state);\n });\n }),\n destroy: function destroy() {\n cleanupModifierEffects();\n isDestroyed = true;\n }\n };\n\n if (!areValidElements(reference, popper)) {\n return instance;\n }\n\n instance.setOptions(options).then(function (state) {\n if (!isDestroyed && options.onFirstUpdate) {\n options.onFirstUpdate(state);\n }\n }); // Modifiers have the ability to execute arbitrary code before the first\n // update cycle runs. They will be executed in the same order as the update\n // cycle. This is useful when a modifier adds some persistent data that\n // other modifiers need to use, but the modifier is run after the dependent\n // one.\n\n function runModifierEffects() {\n state.orderedModifiers.forEach(function (_ref) {\n var name = _ref.name,\n _ref$options = _ref.options,\n options = _ref$options === void 0 ? {} : _ref$options,\n effect = _ref.effect;\n\n if (typeof effect === 'function') {\n var cleanupFn = effect({\n state: state,\n name: name,\n instance: instance,\n options: options\n });\n\n var noopFn = function noopFn() {};\n\n effectCleanupFns.push(cleanupFn || noopFn);\n }\n });\n }\n\n function cleanupModifierEffects() {\n effectCleanupFns.forEach(function (fn) {\n return fn();\n });\n effectCleanupFns = [];\n }\n\n return instance;\n };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };","export default function mergeByName(modifiers) {\n var merged = modifiers.reduce(function (merged, current) {\n var existing = merged[current.name];\n merged[current.name] = existing ? Object.assign({}, existing, current, {\n options: Object.assign({}, existing.options, current.options),\n data: Object.assign({}, existing.data, current.data)\n }) : current;\n return merged;\n }, {}); // IE11 does not support Object.values\n\n return Object.keys(merged).map(function (key) {\n return merged[key];\n });\n}","import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n passive: true\n};\n\nfunction effect(_ref) {\n var state = _ref.state,\n instance = _ref.instance,\n options = _ref.options;\n var _options$scroll = options.scroll,\n scroll = _options$scroll === void 0 ? true : _options$scroll,\n _options$resize = options.resize,\n resize = _options$resize === void 0 ? true : _options$resize;\n var window = getWindow(state.elements.popper);\n var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.addEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.addEventListener('resize', instance.update, passive);\n }\n\n return function () {\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.removeEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.removeEventListener('resize', instance.update, passive);\n }\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'eventListeners',\n enabled: true,\n phase: 'write',\n fn: function fn() {},\n effect: effect,\n data: {}\n};","import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n return placement.split('-')[0];\n}","export default function getVariation(placement) {\n return placement.split('-')[1];\n}","export default function getMainAxisFromPlacement(placement) {\n return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}","import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n var reference = _ref.reference,\n element = _ref.element,\n placement = _ref.placement;\n var basePlacement = placement ? getBasePlacement(placement) : null;\n var variation = placement ? getVariation(placement) : null;\n var commonX = reference.x + reference.width / 2 - element.width / 2;\n var commonY = reference.y + reference.height / 2 - element.height / 2;\n var offsets;\n\n switch (basePlacement) {\n case top:\n offsets = {\n x: commonX,\n y: reference.y - element.height\n };\n break;\n\n case bottom:\n offsets = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n\n case right:\n offsets = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n\n case left:\n offsets = {\n x: reference.x - element.width,\n y: commonY\n };\n break;\n\n default:\n offsets = {\n x: reference.x,\n y: reference.y\n };\n }\n\n var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n if (mainAxis != null) {\n var len = mainAxis === 'y' ? 'height' : 'width';\n\n switch (variation) {\n case start:\n offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n break;\n\n case end:\n offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n break;\n\n default:\n }\n }\n\n return offsets;\n}","import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n var state = _ref.state,\n name = _ref.name;\n // Offsets are the actual position the popper needs to have to be\n // properly positioned near its reference element\n // This is the most basic placement, and will be adjusted by\n // the modifiers in the next step\n state.modifiersData[name] = computeOffsets({\n reference: state.rects.reference,\n element: state.rects.popper,\n strategy: 'absolute',\n placement: state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'popperOffsets',\n enabled: true,\n phase: 'read',\n fn: popperOffsets,\n data: {}\n};","import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n top: 'auto',\n right: 'auto',\n bottom: 'auto',\n left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref, win) {\n var x = _ref.x,\n y = _ref.y;\n var dpr = win.devicePixelRatio || 1;\n return {\n x: round(x * dpr) / dpr || 0,\n y: round(y * dpr) / dpr || 0\n };\n}\n\nexport function mapToStyles(_ref2) {\n var _Object$assign2;\n\n var popper = _ref2.popper,\n popperRect = _ref2.popperRect,\n placement = _ref2.placement,\n variation = _ref2.variation,\n offsets = _ref2.offsets,\n position = _ref2.position,\n gpuAcceleration = _ref2.gpuAcceleration,\n adaptive = _ref2.adaptive,\n roundOffsets = _ref2.roundOffsets,\n isFixed = _ref2.isFixed;\n var _offsets$x = offsets.x,\n x = _offsets$x === void 0 ? 0 : _offsets$x,\n _offsets$y = offsets.y,\n y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref3.x;\n y = _ref3.y;\n var hasX = offsets.hasOwnProperty('x');\n var hasY = offsets.hasOwnProperty('y');\n var sideX = left;\n var sideY = top;\n var win = window;\n\n if (adaptive) {\n var offsetParent = getOffsetParent(popper);\n var heightProp = 'clientHeight';\n var widthProp = 'clientWidth';\n\n if (offsetParent === getWindow(popper)) {\n offsetParent = getDocumentElement(popper);\n\n if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n heightProp = 'scrollHeight';\n widthProp = 'scrollWidth';\n }\n } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n offsetParent = offsetParent;\n\n if (placement === top || (placement === left || placement === right) && variation === end) {\n sideY = bottom;\n var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n offsetParent[heightProp];\n y -= offsetY - popperRect.height;\n y *= gpuAcceleration ? 1 : -1;\n }\n\n if (placement === left || (placement === top || placement === bottom) && variation === end) {\n sideX = right;\n var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n offsetParent[widthProp];\n x -= offsetX - popperRect.width;\n x *= gpuAcceleration ? 1 : -1;\n }\n }\n\n var commonStyles = Object.assign({\n position: position\n }, adaptive && unsetSides);\n\n var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n x: x,\n y: y\n }, getWindow(popper)) : {\n x: x,\n y: y\n };\n\n x = _ref4.x;\n y = _ref4.y;\n\n if (gpuAcceleration) {\n var _Object$assign;\n\n return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? \"translate(\" + x + \"px, \" + y + \"px)\" : \"translate3d(\" + x + \"px, \" + y + \"px, 0)\", _Object$assign));\n }\n\n return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n var state = _ref5.state,\n options = _ref5.options;\n var _options$gpuAccelerat = options.gpuAcceleration,\n gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n _options$adaptive = options.adaptive,\n adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n _options$roundOffsets = options.roundOffsets,\n roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n var commonStyles = {\n placement: getBasePlacement(state.placement),\n variation: getVariation(state.placement),\n popper: state.elements.popper,\n popperRect: state.rects.popper,\n gpuAcceleration: gpuAcceleration,\n isFixed: state.options.strategy === 'fixed'\n };\n\n if (state.modifiersData.popperOffsets != null) {\n state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.popperOffsets,\n position: state.options.strategy,\n adaptive: adaptive,\n roundOffsets: roundOffsets\n })));\n }\n\n if (state.modifiersData.arrow != null) {\n state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.arrow,\n position: 'absolute',\n adaptive: false,\n roundOffsets: roundOffsets\n })));\n }\n\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-placement': state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'computeStyles',\n enabled: true,\n phase: 'beforeWrite',\n fn: computeStyles,\n data: {}\n};","import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n var state = _ref.state;\n Object.keys(state.elements).forEach(function (name) {\n var style = state.styles[name] || {};\n var attributes = state.attributes[name] || {};\n var element = state.elements[name]; // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n } // Flow doesn't support to extend this property, but it's the most\n // effective way to apply styles to an HTMLElement\n // $FlowFixMe[cannot-write]\n\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (name) {\n var value = attributes[name];\n\n if (value === false) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, value === true ? '' : value);\n }\n });\n });\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state;\n var initialStyles = {\n popper: {\n position: state.options.strategy,\n left: '0',\n top: '0',\n margin: '0'\n },\n arrow: {\n position: 'absolute'\n },\n reference: {}\n };\n Object.assign(state.elements.popper.style, initialStyles.popper);\n state.styles = initialStyles;\n\n if (state.elements.arrow) {\n Object.assign(state.elements.arrow.style, initialStyles.arrow);\n }\n\n return function () {\n Object.keys(state.elements).forEach(function (name) {\n var element = state.elements[name];\n var attributes = state.attributes[name] || {};\n var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n var style = styleProperties.reduce(function (style, property) {\n style[property] = '';\n return style;\n }, {}); // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n }\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (attribute) {\n element.removeAttribute(attribute);\n });\n });\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'applyStyles',\n enabled: true,\n phase: 'write',\n fn: applyStyles,\n effect: effect,\n requires: ['computeStyles']\n};","import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n var basePlacement = getBasePlacement(placement);\n var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n placement: placement\n })) : offset,\n skidding = _ref[0],\n distance = _ref[1];\n\n skidding = skidding || 0;\n distance = (distance || 0) * invertDistance;\n return [left, right].indexOf(basePlacement) >= 0 ? {\n x: distance,\n y: skidding\n } : {\n x: skidding,\n y: distance\n };\n}\n\nfunction offset(_ref2) {\n var state = _ref2.state,\n options = _ref2.options,\n name = _ref2.name;\n var _options$offset = options.offset,\n offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n var data = placements.reduce(function (acc, placement) {\n acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n return acc;\n }, {});\n var _data$state$placement = data[state.placement],\n x = _data$state$placement.x,\n y = _data$state$placement.y;\n\n if (state.modifiersData.popperOffsets != null) {\n state.modifiersData.popperOffsets.x += x;\n state.modifiersData.popperOffsets.y += y;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'offset',\n enabled: true,\n phase: 'main',\n requires: ['popperOffsets'],\n fn: offset\n};","var hash = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}","var hash = {\n start: 'end',\n end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n return placement.replace(/start|end/g, function (matched) {\n return hash[matched];\n });\n}","import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n if (parent.contains(child)) {\n return true;\n } // then fallback to custom implementation with Shadow DOM support\n else if (rootNode && isShadowRoot(rootNode)) {\n var next = child;\n\n do {\n if (next && parent.isSameNode(next)) {\n return true;\n } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n next = next.parentNode || next.host;\n } while (next);\n } // Give up, the result is false\n\n\n return false;\n}","export default function rectToClientRect(rect) {\n return Object.assign({}, rect, {\n left: rect.x,\n top: rect.y,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n });\n}","import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element, strategy) {\n var rect = getBoundingClientRect(element, false, strategy === 'fixed');\n rect.top = rect.top + element.clientTop;\n rect.left = rect.left + element.clientLeft;\n rect.bottom = rect.top + element.clientHeight;\n rect.right = rect.left + element.clientWidth;\n rect.width = element.clientWidth;\n rect.height = element.clientHeight;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent, strategy) {\n return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n var clippingParents = listScrollParents(getParentNode(element));\n var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n if (!isElement(clipperElement)) {\n return [];\n } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n return clippingParents.filter(function (clippingParent) {\n return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary, strategy) {\n var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n var firstClippingParent = clippingParents[0];\n var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n var rect = getClientRectFromMixedType(element, clippingParent, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromMixedType(element, firstClippingParent, strategy));\n clippingRect.width = clippingRect.right - clippingRect.left;\n clippingRect.height = clippingRect.bottom - clippingRect.top;\n clippingRect.x = clippingRect.left;\n clippingRect.y = clippingRect.top;\n return clippingRect;\n}","import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getViewportRect(element, strategy) {\n var win = getWindow(element);\n var html = getDocumentElement(element);\n var visualViewport = win.visualViewport;\n var width = html.clientWidth;\n var height = html.clientHeight;\n var x = 0;\n var y = 0;\n\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n var layoutViewport = isLayoutViewport();\n\n if (layoutViewport || !layoutViewport && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n\n return {\n width: width,\n height: height,\n x: x + getWindowScrollBarX(element),\n y: y\n };\n}","import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n var _element$ownerDocumen;\n\n var html = getDocumentElement(element);\n var winScroll = getWindowScroll(element);\n var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n var y = -winScroll.scrollTop;\n\n if (getComputedStyle(body || html).direction === 'rtl') {\n x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n }\n\n return {\n width: width,\n height: height,\n x: x,\n y: y\n };\n}","import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n return Object.assign({}, getFreshSideObject(), paddingObject);\n}","export default function getFreshSideObject() {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n}","export default function expandToHashMap(value, keys) {\n return keys.reduce(function (hashMap, key) {\n hashMap[key] = value;\n return hashMap;\n }, {});\n}","import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$placement = _options.placement,\n placement = _options$placement === void 0 ? state.placement : _options$placement,\n _options$strategy = _options.strategy,\n strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,\n _options$boundary = _options.boundary,\n boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n _options$rootBoundary = _options.rootBoundary,\n rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n _options$elementConte = _options.elementContext,\n elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n _options$altBoundary = _options.altBoundary,\n altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n _options$padding = _options.padding,\n padding = _options$padding === void 0 ? 0 : _options$padding;\n var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n var altContext = elementContext === popper ? reference : popper;\n var popperRect = state.rects.popper;\n var element = state.elements[altBoundary ? altContext : elementContext];\n var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);\n var referenceClientRect = getBoundingClientRect(state.elements.reference);\n var popperOffsets = computeOffsets({\n reference: referenceClientRect,\n element: popperRect,\n strategy: 'absolute',\n placement: placement\n });\n var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n // 0 or negative = within the clipping rect\n\n var overflowOffsets = {\n top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n };\n var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n if (elementContext === popper && offsetData) {\n var offset = offsetData[placement];\n Object.keys(overflowOffsets).forEach(function (key) {\n var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n overflowOffsets[key] += offset[axis] * multiply;\n });\n }\n\n return overflowOffsets;\n}","import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n if (getBasePlacement(placement) === auto) {\n return [];\n }\n\n var oppositePlacement = getOppositePlacement(placement);\n return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n\n if (state.modifiersData[name]._skip) {\n return;\n }\n\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n specifiedFallbackPlacements = options.fallbackPlacements,\n padding = options.padding,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n _options$flipVariatio = options.flipVariations,\n flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n allowedAutoPlacements = options.allowedAutoPlacements;\n var preferredPlacement = state.options.placement;\n var basePlacement = getBasePlacement(preferredPlacement);\n var isBasePlacement = basePlacement === preferredPlacement;\n var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n flipVariations: flipVariations,\n allowedAutoPlacements: allowedAutoPlacements\n }) : placement);\n }, []);\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var checksMap = new Map();\n var makeFallbackChecks = true;\n var firstFittingPlacement = placements[0];\n\n for (var i = 0; i < placements.length; i++) {\n var placement = placements[i];\n\n var _basePlacement = getBasePlacement(placement);\n\n var isStartVariation = getVariation(placement) === start;\n var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n var len = isVertical ? 'width' : 'height';\n var overflow = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n altBoundary: altBoundary,\n padding: padding\n });\n var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n if (referenceRect[len] > popperRect[len]) {\n mainVariationSide = getOppositePlacement(mainVariationSide);\n }\n\n var altVariationSide = getOppositePlacement(mainVariationSide);\n var checks = [];\n\n if (checkMainAxis) {\n checks.push(overflow[_basePlacement] <= 0);\n }\n\n if (checkAltAxis) {\n checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n }\n\n if (checks.every(function (check) {\n return check;\n })) {\n firstFittingPlacement = placement;\n makeFallbackChecks = false;\n break;\n }\n\n checksMap.set(placement, checks);\n }\n\n if (makeFallbackChecks) {\n // `2` may be desired in some cases – research later\n var numberOfChecks = flipVariations ? 3 : 1;\n\n var _loop = function _loop(_i) {\n var fittingPlacement = placements.find(function (placement) {\n var checks = checksMap.get(placement);\n\n if (checks) {\n return checks.slice(0, _i).every(function (check) {\n return check;\n });\n }\n });\n\n if (fittingPlacement) {\n firstFittingPlacement = fittingPlacement;\n return \"break\";\n }\n };\n\n for (var _i = numberOfChecks; _i > 0; _i--) {\n var _ret = _loop(_i);\n\n if (_ret === \"break\") break;\n }\n }\n\n if (state.placement !== firstFittingPlacement) {\n state.modifiersData[name]._skip = true;\n state.placement = firstFittingPlacement;\n state.reset = true;\n }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'flip',\n enabled: true,\n phase: 'main',\n fn: flip,\n requiresIfExists: ['offset'],\n data: {\n _skip: false\n }\n};","import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n placement = _options.placement,\n boundary = _options.boundary,\n rootBoundary = _options.rootBoundary,\n padding = _options.padding,\n flipVariations = _options.flipVariations,\n _options$allowedAutoP = _options.allowedAutoPlacements,\n allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n var variation = getVariation(placement);\n var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n return getVariation(placement) === variation;\n }) : basePlacements;\n var allowedPlacements = placements.filter(function (placement) {\n return allowedAutoPlacements.indexOf(placement) >= 0;\n });\n\n if (allowedPlacements.length === 0) {\n allowedPlacements = placements;\n } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n var overflows = allowedPlacements.reduce(function (acc, placement) {\n acc[placement] = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding\n })[getBasePlacement(placement)];\n return acc;\n }, {});\n return Object.keys(overflows).sort(function (a, b) {\n return overflows[a] - overflows[b];\n });\n}","import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n var v = within(min, value, max);\n return v > max ? max : v;\n}","import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n padding = options.padding,\n _options$tether = options.tether,\n tether = _options$tether === void 0 ? true : _options$tether,\n _options$tetherOffset = options.tetherOffset,\n tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n var overflow = detectOverflow(state, {\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n altBoundary: altBoundary\n });\n var basePlacement = getBasePlacement(state.placement);\n var variation = getVariation(state.placement);\n var isBasePlacement = !variation;\n var mainAxis = getMainAxisFromPlacement(basePlacement);\n var altAxis = getAltAxis(mainAxis);\n var popperOffsets = state.modifiersData.popperOffsets;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n placement: state.placement\n })) : tetherOffset;\n var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n mainAxis: tetherOffsetValue,\n altAxis: tetherOffsetValue\n } : Object.assign({\n mainAxis: 0,\n altAxis: 0\n }, tetherOffsetValue);\n var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n var data = {\n x: 0,\n y: 0\n };\n\n if (!popperOffsets) {\n return;\n }\n\n if (checkMainAxis) {\n var _offsetModifierState$;\n\n var mainSide = mainAxis === 'y' ? top : left;\n var altSide = mainAxis === 'y' ? bottom : right;\n var len = mainAxis === 'y' ? 'height' : 'width';\n var offset = popperOffsets[mainAxis];\n var min = offset + overflow[mainSide];\n var max = offset - overflow[altSide];\n var additive = tether ? -popperRect[len] / 2 : 0;\n var minLen = variation === start ? referenceRect[len] : popperRect[len];\n var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n // outside the reference bounds\n\n var arrowElement = state.elements.arrow;\n var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n width: 0,\n height: 0\n };\n var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n var arrowPaddingMin = arrowPaddingObject[mainSide];\n var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n // to include its full size in the calculation. If the reference is small\n // and near the edge of a boundary, the popper can overflow even if the\n // reference is not overflowing as well (e.g. virtual elements with no\n // width or height)\n\n var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n var tetherMax = offset + maxOffset - offsetModifierValue;\n var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n popperOffsets[mainAxis] = preventedOffset;\n data[mainAxis] = preventedOffset - offset;\n }\n\n if (checkAltAxis) {\n var _offsetModifierState$2;\n\n var _mainSide = mainAxis === 'x' ? top : left;\n\n var _altSide = mainAxis === 'x' ? bottom : right;\n\n var _offset = popperOffsets[altAxis];\n\n var _len = altAxis === 'y' ? 'height' : 'width';\n\n var _min = _offset + overflow[_mainSide];\n\n var _max = _offset - overflow[_altSide];\n\n var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n popperOffsets[altAxis] = _preventedOffset;\n data[altAxis] = _preventedOffset - _offset;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'preventOverflow',\n enabled: true,\n phase: 'main',\n fn: preventOverflow,\n requiresIfExists: ['offset']\n};","export default function getAltAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}","import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n placement: state.placement\n })) : padding;\n return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n var _state$modifiersData$;\n\n var state = _ref.state,\n name = _ref.name,\n options = _ref.options;\n var arrowElement = state.elements.arrow;\n var popperOffsets = state.modifiersData.popperOffsets;\n var basePlacement = getBasePlacement(state.placement);\n var axis = getMainAxisFromPlacement(basePlacement);\n var isVertical = [left, right].indexOf(basePlacement) >= 0;\n var len = isVertical ? 'height' : 'width';\n\n if (!arrowElement || !popperOffsets) {\n return;\n }\n\n var paddingObject = toPaddingObject(options.padding, state);\n var arrowRect = getLayoutRect(arrowElement);\n var minProp = axis === 'y' ? top : left;\n var maxProp = axis === 'y' ? bottom : right;\n var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n var arrowOffsetParent = getOffsetParent(arrowElement);\n var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n // outside of the popper bounds\n\n var min = paddingObject[minProp];\n var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n var axisProp = axis;\n state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state,\n options = _ref2.options;\n var _options$element = options.element,\n arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n if (arrowElement == null) {\n return;\n } // CSS selector\n\n\n if (typeof arrowElement === 'string') {\n arrowElement = state.elements.popper.querySelector(arrowElement);\n\n if (!arrowElement) {\n return;\n }\n }\n\n if (!contains(state.elements.popper, arrowElement)) {\n return;\n }\n\n state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'arrow',\n enabled: true,\n phase: 'main',\n fn: arrow,\n effect: effect,\n requires: ['popperOffsets'],\n requiresIfExists: ['preventOverflow']\n};","import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n if (preventedOffsets === void 0) {\n preventedOffsets = {\n x: 0,\n y: 0\n };\n }\n\n return {\n top: overflow.top - rect.height - preventedOffsets.y,\n right: overflow.right - rect.width + preventedOffsets.x,\n bottom: overflow.bottom - rect.height + preventedOffsets.y,\n left: overflow.left - rect.width - preventedOffsets.x\n };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n return [top, right, bottom, left].some(function (side) {\n return overflow[side] >= 0;\n });\n}\n\nfunction hide(_ref) {\n var state = _ref.state,\n name = _ref.name;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var preventedOffsets = state.modifiersData.preventOverflow;\n var referenceOverflow = detectOverflow(state, {\n elementContext: 'reference'\n });\n var popperAltOverflow = detectOverflow(state, {\n altBoundary: true\n });\n var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n state.modifiersData[name] = {\n referenceClippingOffsets: referenceClippingOffsets,\n popperEscapeOffsets: popperEscapeOffsets,\n isReferenceHidden: isReferenceHidden,\n hasPopperEscaped: hasPopperEscaped\n };\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-reference-hidden': isReferenceHidden,\n 'data-popper-escaped': hasPopperEscaped\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'hide',\n enabled: true,\n phase: 'main',\n requiresIfExists: ['preventOverflow'],\n fn: hide\n};","import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";","'use client';\n\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport { exactProp, HTMLElementType, unstable_useEnhancedEffect as useEnhancedEffect, unstable_useForkRef as useForkRef, unstable_setRef as setRef } from '@mui/utils';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction getContainer(container) {\n return typeof container === 'function' ? container() : container;\n}\n\n/**\n * Portals provide a first-class way to render children into a DOM node\n * that exists outside the DOM hierarchy of the parent component.\n *\n * Demos:\n *\n * - [Portal](https://mui.com/material-ui/react-portal/)\n *\n * API:\n *\n * - [Portal API](https://mui.com/material-ui/api/portal/)\n */\nconst Portal = /*#__PURE__*/React.forwardRef(function Portal(props, forwardedRef) {\n const {\n children,\n container,\n disablePortal = false\n } = props;\n const [mountNode, setMountNode] = React.useState(null);\n // @ts-expect-error TODO upstream fix\n const handleRef = useForkRef( /*#__PURE__*/React.isValidElement(children) ? children.ref : null, forwardedRef);\n useEnhancedEffect(() => {\n if (!disablePortal) {\n setMountNode(getContainer(container) || document.body);\n }\n }, [container, disablePortal]);\n useEnhancedEffect(() => {\n if (mountNode && !disablePortal) {\n setRef(forwardedRef, mountNode);\n return () => {\n setRef(forwardedRef, null);\n };\n }\n return undefined;\n }, [forwardedRef, mountNode, disablePortal]);\n if (disablePortal) {\n if ( /*#__PURE__*/React.isValidElement(children)) {\n const newProps = {\n ref: handleRef\n };\n return /*#__PURE__*/React.cloneElement(children, newProps);\n }\n return /*#__PURE__*/_jsx(React.Fragment, {\n children: children\n });\n }\n return /*#__PURE__*/_jsx(React.Fragment, {\n children: mountNode ? /*#__PURE__*/ReactDOM.createPortal(children, mountNode) : mountNode\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Portal.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The children to render into the `container`.\n */\n children: PropTypes.node,\n /**\n * An HTML element or function that returns one.\n * The `container` will have the portal children appended to it.\n *\n * You can also provide a callback, which is called in a React layout effect.\n * This lets you set the container from a ref, and also makes server-side rendering possible.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * The `children` will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool\n} : void 0;\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n Portal['propTypes' + ''] = exactProp(Portal.propTypes);\n}\nexport default Portal;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getPopperUtilityClass(slot) {\n return generateUtilityClass('MuiPopper', slot);\n}\nconst popperClasses = generateUtilityClasses('MuiPopper', ['root']);\nexport default popperClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"anchorEl\", \"children\", \"direction\", \"disablePortal\", \"modifiers\", \"open\", \"placement\", \"popperOptions\", \"popperRef\", \"slotProps\", \"slots\", \"TransitionProps\", \"ownerState\"],\n _excluded2 = [\"anchorEl\", \"children\", \"container\", \"direction\", \"disablePortal\", \"keepMounted\", \"modifiers\", \"open\", \"placement\", \"popperOptions\", \"popperRef\", \"style\", \"transition\", \"slotProps\", \"slots\"];\nimport * as React from 'react';\nimport { chainPropTypes, HTMLElementType, refType, unstable_ownerDocument as ownerDocument, unstable_useEnhancedEffect as useEnhancedEffect, unstable_useForkRef as useForkRef } from '@mui/utils';\nimport { createPopper } from '@popperjs/core';\nimport PropTypes from 'prop-types';\nimport composeClasses from '@mui/utils/composeClasses';\nimport useSlotProps from '@mui/utils/useSlotProps';\nimport Portal from '../Portal';\nimport { getPopperUtilityClass } from './popperClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction flipPlacement(placement, direction) {\n if (direction === 'ltr') {\n return placement;\n }\n switch (placement) {\n case 'bottom-end':\n return 'bottom-start';\n case 'bottom-start':\n return 'bottom-end';\n case 'top-end':\n return 'top-start';\n case 'top-start':\n return 'top-end';\n default:\n return placement;\n }\n}\nfunction resolveAnchorEl(anchorEl) {\n return typeof anchorEl === 'function' ? anchorEl() : anchorEl;\n}\nfunction isHTMLElement(element) {\n return element.nodeType !== undefined;\n}\nfunction isVirtualElement(element) {\n return !isHTMLElement(element);\n}\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root']\n };\n return composeClasses(slots, getPopperUtilityClass, classes);\n};\nconst defaultPopperOptions = {};\nconst PopperTooltip = /*#__PURE__*/React.forwardRef(function PopperTooltip(props, forwardedRef) {\n var _slots$root;\n const {\n anchorEl,\n children,\n direction,\n disablePortal,\n modifiers,\n open,\n placement: initialPlacement,\n popperOptions,\n popperRef: popperRefProp,\n slotProps = {},\n slots = {},\n TransitionProps\n // @ts-ignore internal logic\n // prevent from spreading to DOM, it can come from the parent component e.g. Select.\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const tooltipRef = React.useRef(null);\n const ownRef = useForkRef(tooltipRef, forwardedRef);\n const popperRef = React.useRef(null);\n const handlePopperRef = useForkRef(popperRef, popperRefProp);\n const handlePopperRefRef = React.useRef(handlePopperRef);\n useEnhancedEffect(() => {\n handlePopperRefRef.current = handlePopperRef;\n }, [handlePopperRef]);\n React.useImperativeHandle(popperRefProp, () => popperRef.current, []);\n const rtlPlacement = flipPlacement(initialPlacement, direction);\n /**\n * placement initialized from prop but can change during lifetime if modifiers.flip.\n * modifiers.flip is essentially a flip for controlled/uncontrolled behavior\n */\n const [placement, setPlacement] = React.useState(rtlPlacement);\n const [resolvedAnchorElement, setResolvedAnchorElement] = React.useState(resolveAnchorEl(anchorEl));\n React.useEffect(() => {\n if (popperRef.current) {\n popperRef.current.forceUpdate();\n }\n });\n React.useEffect(() => {\n if (anchorEl) {\n setResolvedAnchorElement(resolveAnchorEl(anchorEl));\n }\n }, [anchorEl]);\n useEnhancedEffect(() => {\n if (!resolvedAnchorElement || !open) {\n return undefined;\n }\n const handlePopperUpdate = data => {\n setPlacement(data.placement);\n };\n if (process.env.NODE_ENV !== 'production') {\n if (resolvedAnchorElement && isHTMLElement(resolvedAnchorElement) && resolvedAnchorElement.nodeType === 1) {\n const box = resolvedAnchorElement.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n console.warn(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n }\n }\n let popperModifiers = [{\n name: 'preventOverflow',\n options: {\n altBoundary: disablePortal\n }\n }, {\n name: 'flip',\n options: {\n altBoundary: disablePortal\n }\n }, {\n name: 'onUpdate',\n enabled: true,\n phase: 'afterWrite',\n fn: ({\n state\n }) => {\n handlePopperUpdate(state);\n }\n }];\n if (modifiers != null) {\n popperModifiers = popperModifiers.concat(modifiers);\n }\n if (popperOptions && popperOptions.modifiers != null) {\n popperModifiers = popperModifiers.concat(popperOptions.modifiers);\n }\n const popper = createPopper(resolvedAnchorElement, tooltipRef.current, _extends({\n placement: rtlPlacement\n }, popperOptions, {\n modifiers: popperModifiers\n }));\n handlePopperRefRef.current(popper);\n return () => {\n popper.destroy();\n handlePopperRefRef.current(null);\n };\n }, [resolvedAnchorElement, disablePortal, modifiers, open, popperOptions, rtlPlacement]);\n const childProps = {\n placement: placement\n };\n if (TransitionProps !== null) {\n childProps.TransitionProps = TransitionProps;\n }\n const classes = useUtilityClasses(props);\n const Root = (_slots$root = slots.root) != null ? _slots$root : 'div';\n const rootProps = useSlotProps({\n elementType: Root,\n externalSlotProps: slotProps.root,\n externalForwardedProps: other,\n additionalProps: {\n role: 'tooltip',\n ref: ownRef\n },\n ownerState: props,\n className: classes.root\n });\n return /*#__PURE__*/_jsx(Root, _extends({}, rootProps, {\n children: typeof children === 'function' ? children(childProps) : children\n }));\n});\n\n/**\n * @ignore - internal component.\n */\nconst Popper = /*#__PURE__*/React.forwardRef(function Popper(props, forwardedRef) {\n const {\n anchorEl,\n children,\n container: containerProp,\n direction = 'ltr',\n disablePortal = false,\n keepMounted = false,\n modifiers,\n open,\n placement = 'bottom',\n popperOptions = defaultPopperOptions,\n popperRef,\n style,\n transition = false,\n slotProps = {},\n slots = {}\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded2);\n const [exited, setExited] = React.useState(true);\n const handleEnter = () => {\n setExited(false);\n };\n const handleExited = () => {\n setExited(true);\n };\n if (!keepMounted && !open && (!transition || exited)) {\n return null;\n }\n\n // If the container prop is provided, use that\n // If the anchorEl prop is provided, use its parent body element as the container\n // If neither are provided let the Modal take care of choosing the container\n let container;\n if (containerProp) {\n container = containerProp;\n } else if (anchorEl) {\n const resolvedAnchorEl = resolveAnchorEl(anchorEl);\n container = resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) ? ownerDocument(resolvedAnchorEl).body : ownerDocument(null).body;\n }\n const display = !open && keepMounted && (!transition || exited) ? 'none' : undefined;\n const transitionProps = transition ? {\n in: open,\n onEnter: handleEnter,\n onExited: handleExited\n } : undefined;\n return /*#__PURE__*/_jsx(Portal, {\n disablePortal: disablePortal,\n container: container,\n children: /*#__PURE__*/_jsx(PopperTooltip, _extends({\n anchorEl: anchorEl,\n direction: direction,\n disablePortal: disablePortal,\n modifiers: modifiers,\n ref: forwardedRef,\n open: transition ? !exited : open,\n placement: placement,\n popperOptions: popperOptions,\n popperRef: popperRef,\n slotProps: slotProps,\n slots: slots\n }, other, {\n style: _extends({\n // Prevents scroll issue, waiting for Popper.js to add this style once initiated.\n position: 'fixed',\n // Fix Popper.js display issue\n top: 0,\n left: 0,\n display\n }, style),\n TransitionProps: transitionProps,\n children: children\n }))\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Popper.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),\n * or a function that returns either.\n * It's used to set the position of the popper.\n * The return value will passed as the reference object of the Popper instance.\n */\n anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]), props => {\n if (props.open) {\n const resolvedAnchorEl = resolveAnchorEl(props.anchorEl);\n if (resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) && resolvedAnchorEl.nodeType === 1) {\n const box = resolvedAnchorEl.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else if (!resolvedAnchorEl || typeof resolvedAnchorEl.getBoundingClientRect !== 'function' || isVirtualElement(resolvedAnchorEl) && resolvedAnchorEl.contextElement != null && resolvedAnchorEl.contextElement.nodeType !== 1) {\n return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'It should be an HTML element instance or a virtualElement ', '(https://popper.js.org/docs/v2/virtual-elements/).'].join('\\n'));\n }\n }\n return null;\n }),\n /**\n * Popper render function or node.\n */\n children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.node, PropTypes.func]),\n /**\n * An HTML element or function that returns one.\n * The `container` will have the portal children appended to it.\n *\n * You can also provide a callback, which is called in a React layout effect.\n * This lets you set the container from a ref, and also makes server-side rendering possible.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * Direction of the text.\n * @default 'ltr'\n */\n direction: PropTypes.oneOf(['ltr', 'rtl']),\n /**\n * The `children` will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool,\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Popper.\n * @default false\n */\n keepMounted: PropTypes.bool,\n /**\n * Popper.js is based on a \"plugin-like\" architecture,\n * most of its features are fully encapsulated \"modifiers\".\n *\n * A modifier is a function that is called each time Popper.js needs to\n * compute the position of the popper.\n * For this reason, modifiers should be very performant to avoid bottlenecks.\n * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).\n */\n modifiers: PropTypes.arrayOf(PropTypes.shape({\n data: PropTypes.object,\n effect: PropTypes.func,\n enabled: PropTypes.bool,\n fn: PropTypes.func,\n name: PropTypes.any,\n options: PropTypes.object,\n phase: PropTypes.oneOf(['afterMain', 'afterRead', 'afterWrite', 'beforeMain', 'beforeRead', 'beforeWrite', 'main', 'read', 'write']),\n requires: PropTypes.arrayOf(PropTypes.string),\n requiresIfExists: PropTypes.arrayOf(PropTypes.string)\n })),\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * Popper placement.\n * @default 'bottom'\n */\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n /**\n * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.\n * @default {}\n */\n popperOptions: PropTypes.shape({\n modifiers: PropTypes.array,\n onFirstUpdate: PropTypes.func,\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n strategy: PropTypes.oneOf(['absolute', 'fixed'])\n }),\n /**\n * A ref that points to the used popper instance.\n */\n popperRef: refType,\n /**\n * The props used for each slot inside the Popper.\n * @default {}\n */\n slotProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside the Popper.\n * Either a string to use a HTML element or a component.\n * @default {}\n */\n slots: PropTypes.shape({\n root: PropTypes.elementType\n }),\n /**\n * Help supporting a react-transition-group/Transition component.\n * @default false\n */\n transition: PropTypes.bool\n} : void 0;\nexport default Popper;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"anchorEl\", \"component\", \"components\", \"componentsProps\", \"container\", \"disablePortal\", \"keepMounted\", \"modifiers\", \"open\", \"placement\", \"popperOptions\", \"popperRef\", \"transition\", \"slots\", \"slotProps\"];\nimport useTheme from '@mui/system/useThemeWithoutDefault';\nimport refType from '@mui/utils/refType';\nimport HTMLElementType from '@mui/utils/HTMLElementType';\nimport PropTypes from 'prop-types';\nimport * as React from 'react';\nimport BasePopper from './BasePopper';\nimport { styled } from '../styles';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst PopperRoot = styled(BasePopper, {\n name: 'MuiPopper',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({});\n\n/**\n *\n * Demos:\n *\n * - [Autocomplete](https://mui.com/material-ui/react-autocomplete/)\n * - [Menu](https://mui.com/material-ui/react-menu/)\n * - [Popper](https://mui.com/material-ui/react-popper/)\n *\n * API:\n *\n * - [Popper API](https://mui.com/material-ui/api/popper/)\n */\nconst Popper = /*#__PURE__*/React.forwardRef(function Popper(inProps, ref) {\n var _slots$root;\n const theme = useTheme();\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiPopper'\n });\n const {\n anchorEl,\n component,\n components,\n componentsProps,\n container,\n disablePortal,\n keepMounted,\n modifiers,\n open,\n placement,\n popperOptions,\n popperRef,\n transition,\n slots,\n slotProps\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const RootComponent = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : components == null ? void 0 : components.Root;\n const otherProps = _extends({\n anchorEl,\n container,\n disablePortal,\n keepMounted,\n modifiers,\n open,\n placement,\n popperOptions,\n popperRef,\n transition\n }, other);\n return /*#__PURE__*/_jsx(PopperRoot, _extends({\n as: component,\n direction: theme == null ? void 0 : theme.direction,\n slots: {\n root: RootComponent\n },\n slotProps: slotProps != null ? slotProps : componentsProps\n }, otherProps, {\n ref: ref\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Popper.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),\n * or a function that returns either.\n * It's used to set the position of the popper.\n * The return value will passed as the reference object of the Popper instance.\n */\n anchorEl: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]),\n /**\n * Popper render function or node.\n */\n children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.node, PropTypes.func]),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The components used for each slot inside the Popper.\n * Either a string to use a HTML element or a component.\n * @default {}\n */\n components: PropTypes.shape({\n Root: PropTypes.elementType\n }),\n /**\n * The props used for each slot inside the Popper.\n * @default {}\n */\n componentsProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * An HTML element or function that returns one.\n * The `container` will have the portal children appended to it.\n *\n * You can also provide a callback, which is called in a React layout effect.\n * This lets you set the container from a ref, and also makes server-side rendering possible.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * The `children` will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool,\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Popper.\n * @default false\n */\n keepMounted: PropTypes.bool,\n /**\n * Popper.js is based on a \"plugin-like\" architecture,\n * most of its features are fully encapsulated \"modifiers\".\n *\n * A modifier is a function that is called each time Popper.js needs to\n * compute the position of the popper.\n * For this reason, modifiers should be very performant to avoid bottlenecks.\n * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).\n */\n modifiers: PropTypes.arrayOf(PropTypes.shape({\n data: PropTypes.object,\n effect: PropTypes.func,\n enabled: PropTypes.bool,\n fn: PropTypes.func,\n name: PropTypes.any,\n options: PropTypes.object,\n phase: PropTypes.oneOf(['afterMain', 'afterRead', 'afterWrite', 'beforeMain', 'beforeRead', 'beforeWrite', 'main', 'read', 'write']),\n requires: PropTypes.arrayOf(PropTypes.string),\n requiresIfExists: PropTypes.arrayOf(PropTypes.string)\n })),\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * Popper placement.\n * @default 'bottom'\n */\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n /**\n * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.\n * @default {}\n */\n popperOptions: PropTypes.shape({\n modifiers: PropTypes.array,\n onFirstUpdate: PropTypes.func,\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n strategy: PropTypes.oneOf(['absolute', 'fixed'])\n }),\n /**\n * A ref that points to the used popper instance.\n */\n popperRef: refType,\n /**\n * The props used for each slot inside the Popper.\n * @default {}\n */\n slotProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside the Popper.\n * Either a string to use a HTML element or a component.\n * @default {}\n */\n slots: PropTypes.shape({\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * Help supporting a react-transition-group/Transition component.\n * @default false\n */\n transition: PropTypes.bool\n} : void 0;\nexport default Popper;","'use client';\n\nimport * as React from 'react';\nlet globalId = 0;\nfunction useGlobalId(idOverride) {\n const [defaultId, setDefaultId] = React.useState(idOverride);\n const id = idOverride || defaultId;\n React.useEffect(() => {\n if (defaultId == null) {\n // Fallback to this default id when possible.\n // Use the incrementing value for client-side rendering only.\n // We can't use it server-side.\n // If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem\n globalId += 1;\n setDefaultId(`mui-${globalId}`);\n }\n }, [defaultId]);\n return id;\n}\n\n// downstream bundlers may remove unnecessary concatenation, but won't remove toString call -- Workaround for https://github.com/webpack/webpack/issues/14814\nconst maybeReactUseId = React['useId'.toString()];\n/**\n *\n * @example
\n * @param idOverride\n * @returns {string}\n */\nexport default function useId(idOverride) {\n if (maybeReactUseId !== undefined) {\n const reactId = maybeReactUseId();\n return idOverride != null ? idOverride : reactId;\n }\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.\n return useGlobalId(idOverride);\n}","'use client';\n\nimport useId from '@mui/utils/useId';\nexport default useId;","'use client';\n\nimport useControlled from '@mui/utils/useControlled';\nexport default useControlled;","'use client';\n\n/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */\nimport * as React from 'react';\nexport default function useControlled({\n controlled,\n default: defaultProp,\n name,\n state = 'value'\n}) {\n // isControlled is ignored in the hook dependency lists as it should never change.\n const {\n current: isControlled\n } = React.useRef(controlled !== undefined);\n const [valueState, setValue] = React.useState(defaultProp);\n const value = isControlled ? controlled : valueState;\n if (process.env.NODE_ENV !== 'production') {\n React.useEffect(() => {\n if (isControlled !== (controlled !== undefined)) {\n console.error([`MUI: A component is changing the ${isControlled ? '' : 'un'}controlled ${state} state of ${name} to be ${isControlled ? 'un' : ''}controlled.`, 'Elements should not switch from uncontrolled to controlled (or vice versa).', `Decide between using a controlled or uncontrolled ${name} ` + 'element for the lifetime of the component.', \"The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.\", 'More info: https://fb.me/react-controlled-components'].join('\\n'));\n }\n }, [state, name, controlled]);\n const {\n current: defaultValue\n } = React.useRef(defaultProp);\n React.useEffect(() => {\n if (!isControlled && !Object.is(defaultValue, defaultProp)) {\n console.error([`MUI: A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. ` + `To suppress this warning opt to use a controlled ${name}.`].join('\\n'));\n }\n }, [JSON.stringify(defaultProp)]);\n }\n const setValueIfUncontrolled = React.useCallback(newValue => {\n if (!isControlled) {\n setValue(newValue);\n }\n }, []);\n return [value, setValueIfUncontrolled];\n}","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getTooltipUtilityClass(slot) {\n return generateUtilityClass('MuiTooltip', slot);\n}\nconst tooltipClasses = generateUtilityClasses('MuiTooltip', ['popper', 'popperInteractive', 'popperArrow', 'popperClose', 'tooltip', 'tooltipArrow', 'touch', 'tooltipPlacementLeft', 'tooltipPlacementRight', 'tooltipPlacementTop', 'tooltipPlacementBottom', 'arrow']);\nexport default tooltipClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"arrow\", \"children\", \"classes\", \"components\", \"componentsProps\", \"describeChild\", \"disableFocusListener\", \"disableHoverListener\", \"disableInteractive\", \"disableTouchListener\", \"enterDelay\", \"enterNextDelay\", \"enterTouchDelay\", \"followCursor\", \"id\", \"leaveDelay\", \"leaveTouchDelay\", \"onClose\", \"onOpen\", \"open\", \"placement\", \"PopperComponent\", \"PopperProps\", \"slotProps\", \"slots\", \"title\", \"TransitionComponent\", \"TransitionProps\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport useTimeout, { Timeout } from '@mui/utils/useTimeout';\nimport elementAcceptingRef from '@mui/utils/elementAcceptingRef';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport { useRtl } from '@mui/system/RtlProvider';\nimport appendOwnerState from '@mui/utils/appendOwnerState';\nimport { styled, useTheme } from '../styles';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport capitalize from '../utils/capitalize';\nimport Grow from '../Grow';\nimport Popper from '../Popper';\nimport useEventCallback from '../utils/useEventCallback';\nimport useForkRef from '../utils/useForkRef';\nimport useId from '../utils/useId';\nimport useIsFocusVisible from '../utils/useIsFocusVisible';\nimport useControlled from '../utils/useControlled';\nimport tooltipClasses, { getTooltipUtilityClass } from './tooltipClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nfunction round(value) {\n return Math.round(value * 1e5) / 1e5;\n}\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n disableInteractive,\n arrow,\n touch,\n placement\n } = ownerState;\n const slots = {\n popper: ['popper', !disableInteractive && 'popperInteractive', arrow && 'popperArrow'],\n tooltip: ['tooltip', arrow && 'tooltipArrow', touch && 'touch', `tooltipPlacement${capitalize(placement.split('-')[0])}`],\n arrow: ['arrow']\n };\n return composeClasses(slots, getTooltipUtilityClass, classes);\n};\nconst TooltipPopper = styled(Popper, {\n name: 'MuiTooltip',\n slot: 'Popper',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.popper, !ownerState.disableInteractive && styles.popperInteractive, ownerState.arrow && styles.popperArrow, !ownerState.open && styles.popperClose];\n }\n})(({\n theme,\n ownerState,\n open\n}) => _extends({\n zIndex: (theme.vars || theme).zIndex.tooltip,\n pointerEvents: 'none'\n}, !ownerState.disableInteractive && {\n pointerEvents: 'auto'\n}, !open && {\n pointerEvents: 'none'\n}, ownerState.arrow && {\n [`&[data-popper-placement*=\"bottom\"] .${tooltipClasses.arrow}`]: {\n top: 0,\n marginTop: '-0.71em',\n '&::before': {\n transformOrigin: '0 100%'\n }\n },\n [`&[data-popper-placement*=\"top\"] .${tooltipClasses.arrow}`]: {\n bottom: 0,\n marginBottom: '-0.71em',\n '&::before': {\n transformOrigin: '100% 0'\n }\n },\n [`&[data-popper-placement*=\"right\"] .${tooltipClasses.arrow}`]: _extends({}, !ownerState.isRtl ? {\n left: 0,\n marginLeft: '-0.71em'\n } : {\n right: 0,\n marginRight: '-0.71em'\n }, {\n height: '1em',\n width: '0.71em',\n '&::before': {\n transformOrigin: '100% 100%'\n }\n }),\n [`&[data-popper-placement*=\"left\"] .${tooltipClasses.arrow}`]: _extends({}, !ownerState.isRtl ? {\n right: 0,\n marginRight: '-0.71em'\n } : {\n left: 0,\n marginLeft: '-0.71em'\n }, {\n height: '1em',\n width: '0.71em',\n '&::before': {\n transformOrigin: '0 0'\n }\n })\n}));\nconst TooltipTooltip = styled('div', {\n name: 'MuiTooltip',\n slot: 'Tooltip',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.tooltip, ownerState.touch && styles.touch, ownerState.arrow && styles.tooltipArrow, styles[`tooltipPlacement${capitalize(ownerState.placement.split('-')[0])}`]];\n }\n})(({\n theme,\n ownerState\n}) => _extends({\n backgroundColor: theme.vars ? theme.vars.palette.Tooltip.bg : alpha(theme.palette.grey[700], 0.92),\n borderRadius: (theme.vars || theme).shape.borderRadius,\n color: (theme.vars || theme).palette.common.white,\n fontFamily: theme.typography.fontFamily,\n padding: '4px 8px',\n fontSize: theme.typography.pxToRem(11),\n maxWidth: 300,\n margin: 2,\n wordWrap: 'break-word',\n fontWeight: theme.typography.fontWeightMedium\n}, ownerState.arrow && {\n position: 'relative',\n margin: 0\n}, ownerState.touch && {\n padding: '8px 16px',\n fontSize: theme.typography.pxToRem(14),\n lineHeight: `${round(16 / 14)}em`,\n fontWeight: theme.typography.fontWeightRegular\n}, {\n [`.${tooltipClasses.popper}[data-popper-placement*=\"left\"] &`]: _extends({\n transformOrigin: 'right center'\n }, !ownerState.isRtl ? _extends({\n marginRight: '14px'\n }, ownerState.touch && {\n marginRight: '24px'\n }) : _extends({\n marginLeft: '14px'\n }, ownerState.touch && {\n marginLeft: '24px'\n })),\n [`.${tooltipClasses.popper}[data-popper-placement*=\"right\"] &`]: _extends({\n transformOrigin: 'left center'\n }, !ownerState.isRtl ? _extends({\n marginLeft: '14px'\n }, ownerState.touch && {\n marginLeft: '24px'\n }) : _extends({\n marginRight: '14px'\n }, ownerState.touch && {\n marginRight: '24px'\n })),\n [`.${tooltipClasses.popper}[data-popper-placement*=\"top\"] &`]: _extends({\n transformOrigin: 'center bottom',\n marginBottom: '14px'\n }, ownerState.touch && {\n marginBottom: '24px'\n }),\n [`.${tooltipClasses.popper}[data-popper-placement*=\"bottom\"] &`]: _extends({\n transformOrigin: 'center top',\n marginTop: '14px'\n }, ownerState.touch && {\n marginTop: '24px'\n })\n}));\nconst TooltipArrow = styled('span', {\n name: 'MuiTooltip',\n slot: 'Arrow',\n overridesResolver: (props, styles) => styles.arrow\n})(({\n theme\n}) => ({\n overflow: 'hidden',\n position: 'absolute',\n width: '1em',\n height: '0.71em' /* = width / sqrt(2) = (length of the hypotenuse) */,\n boxSizing: 'border-box',\n color: theme.vars ? theme.vars.palette.Tooltip.bg : alpha(theme.palette.grey[700], 0.9),\n '&::before': {\n content: '\"\"',\n margin: 'auto',\n display: 'block',\n width: '100%',\n height: '100%',\n backgroundColor: 'currentColor',\n transform: 'rotate(45deg)'\n }\n}));\nlet hystersisOpen = false;\nconst hystersisTimer = new Timeout();\nlet cursorPosition = {\n x: 0,\n y: 0\n};\nexport function testReset() {\n hystersisOpen = false;\n hystersisTimer.clear();\n}\nfunction composeEventHandler(handler, eventHandler) {\n return (event, ...params) => {\n if (eventHandler) {\n eventHandler(event, ...params);\n }\n handler(event, ...params);\n };\n}\n\n// TODO v6: Remove PopperComponent, PopperProps, TransitionComponent and TransitionProps.\nconst Tooltip = /*#__PURE__*/React.forwardRef(function Tooltip(inProps, ref) {\n var _ref, _slots$popper, _ref2, _ref3, _slots$transition, _ref4, _slots$tooltip, _ref5, _slots$arrow, _slotProps$popper, _ref6, _slotProps$popper2, _slotProps$transition, _slotProps$tooltip, _ref7, _slotProps$tooltip2, _slotProps$arrow, _ref8, _slotProps$arrow2;\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiTooltip'\n });\n const {\n arrow = false,\n children: childrenProp,\n components = {},\n componentsProps = {},\n describeChild = false,\n disableFocusListener = false,\n disableHoverListener = false,\n disableInteractive: disableInteractiveProp = false,\n disableTouchListener = false,\n enterDelay = 100,\n enterNextDelay = 0,\n enterTouchDelay = 700,\n followCursor = false,\n id: idProp,\n leaveDelay = 0,\n leaveTouchDelay = 1500,\n onClose,\n onOpen,\n open: openProp,\n placement = 'bottom',\n PopperComponent: PopperComponentProp,\n PopperProps = {},\n slotProps = {},\n slots = {},\n title,\n TransitionComponent: TransitionComponentProp = Grow,\n TransitionProps\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n\n // to prevent runtime errors, developers will need to provide a child as a React element anyway.\n const children = /*#__PURE__*/React.isValidElement(childrenProp) ? childrenProp : /*#__PURE__*/_jsx(\"span\", {\n children: childrenProp\n });\n const theme = useTheme();\n const isRtl = useRtl();\n const [childNode, setChildNode] = React.useState();\n const [arrowRef, setArrowRef] = React.useState(null);\n const ignoreNonTouchEvents = React.useRef(false);\n const disableInteractive = disableInteractiveProp || followCursor;\n const closeTimer = useTimeout();\n const enterTimer = useTimeout();\n const leaveTimer = useTimeout();\n const touchTimer = useTimeout();\n const [openState, setOpenState] = useControlled({\n controlled: openProp,\n default: false,\n name: 'Tooltip',\n state: 'open'\n });\n let open = openState;\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const {\n current: isControlled\n } = React.useRef(openProp !== undefined);\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(() => {\n if (childNode && childNode.disabled && !isControlled && title !== '' && childNode.tagName.toLowerCase() === 'button') {\n console.error(['MUI: You are providing a disabled `button` child to the Tooltip component.', 'A disabled element does not fire events.', \"Tooltip needs to listen to the child element's events to display the title.\", '', 'Add a simple wrapper element, such as a `span`.'].join('\\n'));\n }\n }, [title, childNode, isControlled]);\n }\n const id = useId(idProp);\n const prevUserSelect = React.useRef();\n const stopTouchInteraction = useEventCallback(() => {\n if (prevUserSelect.current !== undefined) {\n document.body.style.WebkitUserSelect = prevUserSelect.current;\n prevUserSelect.current = undefined;\n }\n touchTimer.clear();\n });\n React.useEffect(() => stopTouchInteraction, [stopTouchInteraction]);\n const handleOpen = event => {\n hystersisTimer.clear();\n hystersisOpen = true;\n\n // The mouseover event will trigger for every nested element in the tooltip.\n // We can skip rerendering when the tooltip is already open.\n // We are using the mouseover event instead of the mouseenter event to fix a hide/show issue.\n setOpenState(true);\n if (onOpen && !open) {\n onOpen(event);\n }\n };\n const handleClose = useEventCallback(\n /**\n * @param {React.SyntheticEvent | Event} event\n */\n event => {\n hystersisTimer.start(800 + leaveDelay, () => {\n hystersisOpen = false;\n });\n setOpenState(false);\n if (onClose && open) {\n onClose(event);\n }\n closeTimer.start(theme.transitions.duration.shortest, () => {\n ignoreNonTouchEvents.current = false;\n });\n });\n const handleMouseOver = event => {\n if (ignoreNonTouchEvents.current && event.type !== 'touchstart') {\n return;\n }\n\n // Remove the title ahead of time.\n // We don't want to wait for the next render commit.\n // We would risk displaying two tooltips at the same time (native + this one).\n if (childNode) {\n childNode.removeAttribute('title');\n }\n enterTimer.clear();\n leaveTimer.clear();\n if (enterDelay || hystersisOpen && enterNextDelay) {\n enterTimer.start(hystersisOpen ? enterNextDelay : enterDelay, () => {\n handleOpen(event);\n });\n } else {\n handleOpen(event);\n }\n };\n const handleMouseLeave = event => {\n enterTimer.clear();\n leaveTimer.start(leaveDelay, () => {\n handleClose(event);\n });\n };\n const {\n isFocusVisibleRef,\n onBlur: handleBlurVisible,\n onFocus: handleFocusVisible,\n ref: focusVisibleRef\n } = useIsFocusVisible();\n // We don't necessarily care about the focusVisible state (which is safe to access via ref anyway).\n // We just need to re-render the Tooltip if the focus-visible state changes.\n const [, setChildIsFocusVisible] = React.useState(false);\n const handleBlur = event => {\n handleBlurVisible(event);\n if (isFocusVisibleRef.current === false) {\n setChildIsFocusVisible(false);\n handleMouseLeave(event);\n }\n };\n const handleFocus = event => {\n // Workaround for https://github.com/facebook/react/issues/7769\n // The autoFocus of React might trigger the event before the componentDidMount.\n // We need to account for this eventuality.\n if (!childNode) {\n setChildNode(event.currentTarget);\n }\n handleFocusVisible(event);\n if (isFocusVisibleRef.current === true) {\n setChildIsFocusVisible(true);\n handleMouseOver(event);\n }\n };\n const detectTouchStart = event => {\n ignoreNonTouchEvents.current = true;\n const childrenProps = children.props;\n if (childrenProps.onTouchStart) {\n childrenProps.onTouchStart(event);\n }\n };\n const handleTouchStart = event => {\n detectTouchStart(event);\n leaveTimer.clear();\n closeTimer.clear();\n stopTouchInteraction();\n prevUserSelect.current = document.body.style.WebkitUserSelect;\n // Prevent iOS text selection on long-tap.\n document.body.style.WebkitUserSelect = 'none';\n touchTimer.start(enterTouchDelay, () => {\n document.body.style.WebkitUserSelect = prevUserSelect.current;\n handleMouseOver(event);\n });\n };\n const handleTouchEnd = event => {\n if (children.props.onTouchEnd) {\n children.props.onTouchEnd(event);\n }\n stopTouchInteraction();\n leaveTimer.start(leaveTouchDelay, () => {\n handleClose(event);\n });\n };\n React.useEffect(() => {\n if (!open) {\n return undefined;\n }\n\n /**\n * @param {KeyboardEvent} nativeEvent\n */\n function handleKeyDown(nativeEvent) {\n // IE11, Edge (prior to using Bink?) use 'Esc'\n if (nativeEvent.key === 'Escape' || nativeEvent.key === 'Esc') {\n handleClose(nativeEvent);\n }\n }\n document.addEventListener('keydown', handleKeyDown);\n return () => {\n document.removeEventListener('keydown', handleKeyDown);\n };\n }, [handleClose, open]);\n const handleRef = useForkRef(children.ref, focusVisibleRef, setChildNode, ref);\n\n // There is no point in displaying an empty tooltip.\n // So we exclude all falsy values, except 0, which is valid.\n if (!title && title !== 0) {\n open = false;\n }\n const popperRef = React.useRef();\n const handleMouseMove = event => {\n const childrenProps = children.props;\n if (childrenProps.onMouseMove) {\n childrenProps.onMouseMove(event);\n }\n cursorPosition = {\n x: event.clientX,\n y: event.clientY\n };\n if (popperRef.current) {\n popperRef.current.update();\n }\n };\n const nameOrDescProps = {};\n const titleIsString = typeof title === 'string';\n if (describeChild) {\n nameOrDescProps.title = !open && titleIsString && !disableHoverListener ? title : null;\n nameOrDescProps['aria-describedby'] = open ? id : null;\n } else {\n nameOrDescProps['aria-label'] = titleIsString ? title : null;\n nameOrDescProps['aria-labelledby'] = open && !titleIsString ? id : null;\n }\n const childrenProps = _extends({}, nameOrDescProps, other, children.props, {\n className: clsx(other.className, children.props.className),\n onTouchStart: detectTouchStart,\n ref: handleRef\n }, followCursor ? {\n onMouseMove: handleMouseMove\n } : {});\n if (process.env.NODE_ENV !== 'production') {\n childrenProps['data-mui-internal-clone-element'] = true;\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(() => {\n if (childNode && !childNode.getAttribute('data-mui-internal-clone-element')) {\n console.error(['MUI: The `children` component of the Tooltip is not forwarding its props correctly.', 'Please make sure that props are spread on the same element that the ref is applied to.'].join('\\n'));\n }\n }, [childNode]);\n }\n const interactiveWrapperListeners = {};\n if (!disableTouchListener) {\n childrenProps.onTouchStart = handleTouchStart;\n childrenProps.onTouchEnd = handleTouchEnd;\n }\n if (!disableHoverListener) {\n childrenProps.onMouseOver = composeEventHandler(handleMouseOver, childrenProps.onMouseOver);\n childrenProps.onMouseLeave = composeEventHandler(handleMouseLeave, childrenProps.onMouseLeave);\n if (!disableInteractive) {\n interactiveWrapperListeners.onMouseOver = handleMouseOver;\n interactiveWrapperListeners.onMouseLeave = handleMouseLeave;\n }\n }\n if (!disableFocusListener) {\n childrenProps.onFocus = composeEventHandler(handleFocus, childrenProps.onFocus);\n childrenProps.onBlur = composeEventHandler(handleBlur, childrenProps.onBlur);\n if (!disableInteractive) {\n interactiveWrapperListeners.onFocus = handleFocus;\n interactiveWrapperListeners.onBlur = handleBlur;\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n if (children.props.title) {\n console.error(['MUI: You have provided a `title` prop to the child of .', `Remove this title prop \\`${children.props.title}\\` or the Tooltip component.`].join('\\n'));\n }\n }\n const popperOptions = React.useMemo(() => {\n var _PopperProps$popperOp;\n let tooltipModifiers = [{\n name: 'arrow',\n enabled: Boolean(arrowRef),\n options: {\n element: arrowRef,\n padding: 4\n }\n }];\n if ((_PopperProps$popperOp = PopperProps.popperOptions) != null && _PopperProps$popperOp.modifiers) {\n tooltipModifiers = tooltipModifiers.concat(PopperProps.popperOptions.modifiers);\n }\n return _extends({}, PopperProps.popperOptions, {\n modifiers: tooltipModifiers\n });\n }, [arrowRef, PopperProps]);\n const ownerState = _extends({}, props, {\n isRtl,\n arrow,\n disableInteractive,\n placement,\n PopperComponentProp,\n touch: ignoreNonTouchEvents.current\n });\n const classes = useUtilityClasses(ownerState);\n const PopperComponent = (_ref = (_slots$popper = slots.popper) != null ? _slots$popper : components.Popper) != null ? _ref : TooltipPopper;\n const TransitionComponent = (_ref2 = (_ref3 = (_slots$transition = slots.transition) != null ? _slots$transition : components.Transition) != null ? _ref3 : TransitionComponentProp) != null ? _ref2 : Grow;\n const TooltipComponent = (_ref4 = (_slots$tooltip = slots.tooltip) != null ? _slots$tooltip : components.Tooltip) != null ? _ref4 : TooltipTooltip;\n const ArrowComponent = (_ref5 = (_slots$arrow = slots.arrow) != null ? _slots$arrow : components.Arrow) != null ? _ref5 : TooltipArrow;\n const popperProps = appendOwnerState(PopperComponent, _extends({}, PopperProps, (_slotProps$popper = slotProps.popper) != null ? _slotProps$popper : componentsProps.popper, {\n className: clsx(classes.popper, PopperProps == null ? void 0 : PopperProps.className, (_ref6 = (_slotProps$popper2 = slotProps.popper) != null ? _slotProps$popper2 : componentsProps.popper) == null ? void 0 : _ref6.className)\n }), ownerState);\n const transitionProps = appendOwnerState(TransitionComponent, _extends({}, TransitionProps, (_slotProps$transition = slotProps.transition) != null ? _slotProps$transition : componentsProps.transition), ownerState);\n const tooltipProps = appendOwnerState(TooltipComponent, _extends({}, (_slotProps$tooltip = slotProps.tooltip) != null ? _slotProps$tooltip : componentsProps.tooltip, {\n className: clsx(classes.tooltip, (_ref7 = (_slotProps$tooltip2 = slotProps.tooltip) != null ? _slotProps$tooltip2 : componentsProps.tooltip) == null ? void 0 : _ref7.className)\n }), ownerState);\n const tooltipArrowProps = appendOwnerState(ArrowComponent, _extends({}, (_slotProps$arrow = slotProps.arrow) != null ? _slotProps$arrow : componentsProps.arrow, {\n className: clsx(classes.arrow, (_ref8 = (_slotProps$arrow2 = slotProps.arrow) != null ? _slotProps$arrow2 : componentsProps.arrow) == null ? void 0 : _ref8.className)\n }), ownerState);\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [/*#__PURE__*/React.cloneElement(children, childrenProps), /*#__PURE__*/_jsx(PopperComponent, _extends({\n as: PopperComponentProp != null ? PopperComponentProp : Popper,\n placement: placement,\n anchorEl: followCursor ? {\n getBoundingClientRect: () => ({\n top: cursorPosition.y,\n left: cursorPosition.x,\n right: cursorPosition.x,\n bottom: cursorPosition.y,\n width: 0,\n height: 0\n })\n } : childNode,\n popperRef: popperRef,\n open: childNode ? open : false,\n id: id,\n transition: true\n }, interactiveWrapperListeners, popperProps, {\n popperOptions: popperOptions,\n children: ({\n TransitionProps: TransitionPropsInner\n }) => /*#__PURE__*/_jsx(TransitionComponent, _extends({\n timeout: theme.transitions.duration.shorter\n }, TransitionPropsInner, transitionProps, {\n children: /*#__PURE__*/_jsxs(TooltipComponent, _extends({}, tooltipProps, {\n children: [title, arrow ? /*#__PURE__*/_jsx(ArrowComponent, _extends({}, tooltipArrowProps, {\n ref: setArrowRef\n })) : null]\n }))\n }))\n }))]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Tooltip.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * If `true`, adds an arrow to the tooltip.\n * @default false\n */\n arrow: PropTypes.bool,\n /**\n * Tooltip reference element.\n */\n children: elementAcceptingRef.isRequired,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The components used for each slot inside.\n *\n * This prop is an alias for the `slots` prop.\n * It's recommended to use the `slots` prop instead.\n *\n * @default {}\n */\n components: PropTypes.shape({\n Arrow: PropTypes.elementType,\n Popper: PropTypes.elementType,\n Tooltip: PropTypes.elementType,\n Transition: PropTypes.elementType\n }),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * This prop is an alias for the `slotProps` prop.\n * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.\n *\n * @default {}\n */\n componentsProps: PropTypes.shape({\n arrow: PropTypes.object,\n popper: PropTypes.object,\n tooltip: PropTypes.object,\n transition: PropTypes.object\n }),\n /**\n * Set to `true` if the `title` acts as an accessible description.\n * By default the `title` acts as an accessible label for the child.\n * @default false\n */\n describeChild: PropTypes.bool,\n /**\n * Do not respond to focus-visible events.\n * @default false\n */\n disableFocusListener: PropTypes.bool,\n /**\n * Do not respond to hover events.\n * @default false\n */\n disableHoverListener: PropTypes.bool,\n /**\n * Makes a tooltip not interactive, i.e. it will close when the user\n * hovers over the tooltip before the `leaveDelay` is expired.\n * @default false\n */\n disableInteractive: PropTypes.bool,\n /**\n * Do not respond to long press touch events.\n * @default false\n */\n disableTouchListener: PropTypes.bool,\n /**\n * The number of milliseconds to wait before showing the tooltip.\n * This prop won't impact the enter touch delay (`enterTouchDelay`).\n * @default 100\n */\n enterDelay: PropTypes.number,\n /**\n * The number of milliseconds to wait before showing the tooltip when one was already recently opened.\n * @default 0\n */\n enterNextDelay: PropTypes.number,\n /**\n * The number of milliseconds a user must touch the element before showing the tooltip.\n * @default 700\n */\n enterTouchDelay: PropTypes.number,\n /**\n * If `true`, the tooltip follow the cursor over the wrapped element.\n * @default false\n */\n followCursor: PropTypes.bool,\n /**\n * This prop is used to help implement the accessibility logic.\n * If you don't provide this prop. It falls back to a randomly generated id.\n */\n id: PropTypes.string,\n /**\n * The number of milliseconds to wait before hiding the tooltip.\n * This prop won't impact the leave touch delay (`leaveTouchDelay`).\n * @default 0\n */\n leaveDelay: PropTypes.number,\n /**\n * The number of milliseconds after the user stops touching an element before hiding the tooltip.\n * @default 1500\n */\n leaveTouchDelay: PropTypes.number,\n /**\n * Callback fired when the component requests to be closed.\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n */\n onClose: PropTypes.func,\n /**\n * Callback fired when the component requests to be open.\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n */\n onOpen: PropTypes.func,\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool,\n /**\n * Tooltip placement.\n * @default 'bottom'\n */\n placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n /**\n * The component used for the popper.\n * @default Popper\n */\n PopperComponent: PropTypes.elementType,\n /**\n * Props applied to the [`Popper`](/material-ui/api/popper/) element.\n * @default {}\n */\n PopperProps: PropTypes.object,\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.\n *\n * @default {}\n */\n slotProps: PropTypes.shape({\n arrow: PropTypes.object,\n popper: PropTypes.object,\n tooltip: PropTypes.object,\n transition: PropTypes.object\n }),\n /**\n * The components used for each slot inside.\n *\n * This prop is an alias for the `components` prop, which will be deprecated in the future.\n *\n * @default {}\n */\n slots: PropTypes.shape({\n arrow: PropTypes.elementType,\n popper: PropTypes.elementType,\n tooltip: PropTypes.elementType,\n transition: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * Tooltip title. Zero-length titles string, undefined, null and false are never displayed.\n */\n title: PropTypes.node,\n /**\n * The component used for the transition.\n * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.\n * @default Grow\n */\n TransitionComponent: PropTypes.elementType,\n /**\n * Props applied to the transition element.\n * By default, the element is based on this [`Transition`](https://reactcommunity.org/react-transition-group/transition/) component.\n */\n TransitionProps: PropTypes.object\n} : void 0;\nexport default Tooltip;","export function getTimeFromSeconds(secs: number) {\n const totalSeconds = Math.ceil(secs);\n const days = Math.floor(totalSeconds / (60 * 60 * 24));\n const hours = Math.floor((totalSeconds % (60 * 60 * 24)) / (60 * 60));\n const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);\n const seconds = Math.floor(totalSeconds % 60);\n\n return {\n totalSeconds,\n seconds,\n minutes,\n hours,\n days,\n };\n}\n\nexport function getSecondsFromExpiry(expiry: Date, shouldRound?: boolean) {\n const now = new Date().getTime();\n const milliSecondsDistance = expiry.getTime() - now;\n if (milliSecondsDistance > 0) {\n const val = milliSecondsDistance / 1000;\n return shouldRound ? Math.round(val) : val;\n }\n return 0;\n}\n\nexport function validateExpiryTimestamp(expiryTimestamp: Date) {\n const isValid = new Date(expiryTimestamp).getTime() > 0;\n if (!isValid) {\n console.warn('useTimer Invalid expiryTimestamp settings', expiryTimestamp); // eslint-disable-line\n }\n return isValid;\n}\n\nexport function validateOnExpire(onExpire: Function) {\n const isValid = onExpire && typeof onExpire === 'function';\n if (onExpire && !isValid) {\n console.warn('useTimer Invalid onExpire settings function', onExpire);\n }\n return isValid;\n}\n\nexport function getDelayFromExpiryTimestamp(\n expiryTimestamp: Date,\n defaultDelay: number,\n) {\n if (!validateExpiryTimestamp(expiryTimestamp)) {\n return 0;\n }\n\n const seconds = getSecondsFromExpiry(expiryTimestamp);\n const extraMilliSeconds = Math.floor((seconds - Math.floor(seconds)) * 1000);\n return extraMilliSeconds > 0 ? extraMilliSeconds : defaultDelay;\n}\n","import { useCallback, useState } from 'react';\nimport { useInterval } from './useInterval.js';\nimport {\n getDelayFromExpiryTimestamp,\n getSecondsFromExpiry,\n getTimeFromSeconds,\n validateOnExpire,\n} from './utils.js';\n\nconst DEFAULT_DELAY = 1000;\n\ninterface UseTimerProps {\n expiryTimestamp: Date;\n onExpire: Function;\n autoStart?: boolean;\n}\n\n// This implementation was taken from the common js project - https://www.npmjs.com/package/react-timer-hook\n// modified to work in the Widget codebase with Typescript\nexport function useTimer({\n expiryTimestamp: expiry,\n onExpire,\n autoStart = true,\n}: UseTimerProps) {\n const [expiryTimestamp, setExpiryTimestamp] = useState(expiry);\n const [seconds, setSeconds] = useState(() =>\n getSecondsFromExpiry(expiryTimestamp),\n );\n const [isRunning, setIsRunning] = useState(autoStart);\n const [didStart, setDidStart] = useState(autoStart);\n const [delay, setDelay] = useState(() =>\n getDelayFromExpiryTimestamp(expiryTimestamp, DEFAULT_DELAY),\n );\n\n const handleExpire = useCallback(() => {\n validateOnExpire(onExpire) && onExpire();\n setIsRunning(false);\n setDelay(0);\n }, [onExpire]);\n\n const pause = useCallback(() => {\n setIsRunning(false);\n }, []);\n\n const restart = useCallback(\n (newExpiryTimestamp: Date, newAutoStart = true) => {\n setDelay(getDelayFromExpiryTimestamp(newExpiryTimestamp, DEFAULT_DELAY));\n setDidStart(newAutoStart);\n setIsRunning(newAutoStart);\n setExpiryTimestamp(newExpiryTimestamp);\n setSeconds(getSecondsFromExpiry(newExpiryTimestamp));\n },\n [],\n );\n\n const resume = useCallback(() => {\n const time = new Date();\n time.setMilliseconds(time.getMilliseconds() + seconds * 1000);\n restart(time);\n }, [seconds, restart]);\n\n const start = useCallback(() => {\n if (didStart) {\n setSeconds(getSecondsFromExpiry(expiryTimestamp));\n setIsRunning(true);\n } else {\n resume();\n }\n }, [expiryTimestamp, didStart, resume]);\n\n useInterval(\n () => {\n if (delay !== DEFAULT_DELAY) {\n setDelay(DEFAULT_DELAY);\n }\n const secondsValue = getSecondsFromExpiry(expiryTimestamp);\n setSeconds(secondsValue);\n if (secondsValue <= 0) {\n handleExpire();\n }\n },\n isRunning ? delay : 0,\n );\n\n return {\n ...getTimeFromSeconds(seconds),\n start,\n pause,\n resume,\n restart,\n isRunning,\n };\n}\n","import { useEffect, useRef } from 'react';\n\nexport function useInterval(callback: Function, delay: number) {\n const callbacRef = useRef();\n\n // update callback function with current render callback that has access to latest props and state\n useEffect(() => {\n callbacRef.current = callback;\n });\n\n useEffect(() => {\n if (!delay) {\n return () => {};\n }\n\n const interval = setInterval(() => {\n callbacRef.current && callbacRef.current();\n }, delay);\n return () => clearInterval(interval);\n }, [delay]);\n}\n","import { alpha, Box, styled } from '@mui/material';\n\nexport const IconTypography = styled(Box)(({ theme }) => ({\n color:\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, 0.32)\n : alpha(theme.palette.common.white, 0.4),\n lineHeight: 0,\n}));\n","import type { LiFiStepExtended } from '@lifi/sdk';\nimport { AccessTimeFilled } from '@mui/icons-material';\nimport { Box, Tooltip } from '@mui/material';\nimport { useEffect, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useTimer } from '../../hooks/timer/useTimer.js';\nimport { IconTypography } from '../IconTypography.js';\n\nconst getExecutionProcess = (step: LiFiStepExtended) =>\n step.execution?.process.findLast(\n (process) =>\n process.type === 'SWAP' ||\n process.type === 'CROSS_CHAIN' ||\n process.type === 'RECEIVING_CHAIN',\n );\n\nconst getExpiryTimestamp = (step: LiFiStepExtended) =>\n new Date(\n (getExecutionProcess(step)?.startedAt ?? Date.now()) +\n step.estimate.executionDuration * 1000,\n );\n\nexport const StepTimer: React.FC<{\n step: LiFiStepExtended;\n hideInProgress?: boolean;\n}> = ({ step, hideInProgress }) => {\n const { t, i18n } = useTranslation();\n const [isExpired, setExpired] = useState(false);\n const [isExecutionStarted, setExecutionStarted] = useState(\n () => !!getExecutionProcess(step),\n );\n const [expiryTimestamp, setExpiryTimestamp] = useState(() =>\n getExpiryTimestamp(step),\n );\n const { seconds, minutes, isRunning, pause, resume, restart } = useTimer({\n autoStart: false,\n expiryTimestamp,\n onExpire: () => setExpired(true),\n });\n\n useEffect(() => {\n const executionProcess = getExecutionProcess(step);\n if (!executionProcess) {\n return;\n }\n const shouldRestart = executionProcess.status === 'FAILED';\n const shouldPause = executionProcess.status === 'ACTION_REQUIRED';\n const shouldStart =\n executionProcess.status === 'STARTED' ||\n executionProcess.status === 'PENDING';\n const shouldResume = executionProcess.status === 'PENDING';\n if (isExecutionStarted && shouldRestart) {\n setExecutionStarted(false);\n setExpired(false);\n return;\n }\n if (isExecutionStarted && isExpired) {\n return;\n }\n if (!isExecutionStarted && shouldStart) {\n const expiryTimestamp = getExpiryTimestamp(step);\n setExecutionStarted(true);\n setExpired(false);\n setExpiryTimestamp(expiryTimestamp);\n restart(expiryTimestamp);\n return;\n }\n if (isRunning && shouldPause) {\n pause();\n } else if (!isRunning && shouldResume) {\n resume();\n }\n }, [isExecutionStarted, isExpired, isRunning, pause, restart, resume, step]);\n\n if (!isExecutionStarted) {\n const showSeconds = step.estimate.executionDuration < 60;\n const duration = showSeconds\n ? Math.floor(step.estimate.executionDuration)\n : Math.floor(step.estimate.executionDuration / 60);\n return (\n \n \n \n \n \n \n {duration.toLocaleString(i18n.language, {\n style: 'unit',\n unit: showSeconds ? 'second' : 'minute',\n unitDisplay: 'narrow',\n })}\n \n \n \n );\n }\n\n const isTimerExpired = isExpired || (!minutes && !seconds);\n\n if (\n step.execution?.status === 'DONE' ||\n step.execution?.status === 'FAILED' ||\n (isTimerExpired && hideInProgress)\n ) {\n return null;\n }\n\n return isTimerExpired ? (\n t('main.inProgress')\n ) : (\n \n \n \n \n \n {`${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`}\n \n \n );\n};\n","'use client';\n\nimport useEnhancedEffect from '@mui/utils/useEnhancedEffect';\nexport default useEnhancedEffect;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getListItemButtonUtilityClass(slot) {\n return generateUtilityClass('MuiListItemButton', slot);\n}\nconst listItemButtonClasses = generateUtilityClasses('MuiListItemButton', ['root', 'focusVisible', 'dense', 'alignItemsFlexStart', 'disabled', 'divider', 'gutters', 'selected']);\nexport default listItemButtonClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"alignItems\", \"autoFocus\", \"component\", \"children\", \"dense\", \"disableGutters\", \"divider\", \"focusVisibleClassName\", \"selected\", \"className\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport styled, { rootShouldForwardProp } from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport ButtonBase from '../ButtonBase';\nimport useEnhancedEffect from '../utils/useEnhancedEffect';\nimport useForkRef from '../utils/useForkRef';\nimport ListContext from '../List/ListContext';\nimport listItemButtonClasses, { getListItemButtonUtilityClass } from './listItemButtonClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const overridesResolver = (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.dense && styles.dense, ownerState.alignItems === 'flex-start' && styles.alignItemsFlexStart, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters];\n};\nconst useUtilityClasses = ownerState => {\n const {\n alignItems,\n classes,\n dense,\n disabled,\n disableGutters,\n divider,\n selected\n } = ownerState;\n const slots = {\n root: ['root', dense && 'dense', !disableGutters && 'gutters', divider && 'divider', disabled && 'disabled', alignItems === 'flex-start' && 'alignItemsFlexStart', selected && 'selected']\n };\n const composedClasses = composeClasses(slots, getListItemButtonUtilityClass, classes);\n return _extends({}, classes, composedClasses);\n};\nconst ListItemButtonRoot = styled(ButtonBase, {\n shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',\n name: 'MuiListItemButton',\n slot: 'Root',\n overridesResolver\n})(({\n theme,\n ownerState\n}) => _extends({\n display: 'flex',\n flexGrow: 1,\n justifyContent: 'flex-start',\n alignItems: 'center',\n position: 'relative',\n textDecoration: 'none',\n minWidth: 0,\n boxSizing: 'border-box',\n textAlign: 'left',\n paddingTop: 8,\n paddingBottom: 8,\n transition: theme.transitions.create('background-color', {\n duration: theme.transitions.duration.shortest\n }),\n '&:hover': {\n textDecoration: 'none',\n backgroundColor: (theme.vars || theme).palette.action.hover,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n },\n [`&.${listItemButtonClasses.selected}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),\n [`&.${listItemButtonClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)\n }\n },\n [`&.${listItemButtonClasses.selected}:hover`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)\n }\n },\n [`&.${listItemButtonClasses.focusVisible}`]: {\n backgroundColor: (theme.vars || theme).palette.action.focus\n },\n [`&.${listItemButtonClasses.disabled}`]: {\n opacity: (theme.vars || theme).palette.action.disabledOpacity\n }\n}, ownerState.divider && {\n borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,\n backgroundClip: 'padding-box'\n}, ownerState.alignItems === 'flex-start' && {\n alignItems: 'flex-start'\n}, !ownerState.disableGutters && {\n paddingLeft: 16,\n paddingRight: 16\n}, ownerState.dense && {\n paddingTop: 4,\n paddingBottom: 4\n}));\nconst ListItemButton = /*#__PURE__*/React.forwardRef(function ListItemButton(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiListItemButton'\n });\n const {\n alignItems = 'center',\n autoFocus = false,\n component = 'div',\n children,\n dense = false,\n disableGutters = false,\n divider = false,\n focusVisibleClassName,\n selected = false,\n className\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const context = React.useContext(ListContext);\n const childContext = React.useMemo(() => ({\n dense: dense || context.dense || false,\n alignItems,\n disableGutters\n }), [alignItems, context.dense, dense, disableGutters]);\n const listItemRef = React.useRef(null);\n useEnhancedEffect(() => {\n if (autoFocus) {\n if (listItemRef.current) {\n listItemRef.current.focus();\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('MUI: Unable to set focus to a ListItemButton whose component has not been rendered.');\n }\n }\n }, [autoFocus]);\n const ownerState = _extends({}, props, {\n alignItems,\n dense: childContext.dense,\n disableGutters,\n divider,\n selected\n });\n const classes = useUtilityClasses(ownerState);\n const handleRef = useForkRef(listItemRef, ref);\n return /*#__PURE__*/_jsx(ListContext.Provider, {\n value: childContext,\n children: /*#__PURE__*/_jsx(ListItemButtonRoot, _extends({\n ref: handleRef,\n href: other.href || other.to\n // `ButtonBase` processes `href` or `to` if `component` is set to 'button'\n ,\n component: (other.href || other.to) && component === 'div' ? 'button' : component,\n focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),\n ownerState: ownerState,\n className: clsx(classes.root, className)\n }, other, {\n classes: classes,\n children: children\n }))\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? ListItemButton.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Defines the `align-items` style property.\n * @default 'center'\n */\n alignItems: PropTypes.oneOf(['center', 'flex-start']),\n /**\n * If `true`, the list item is focused during the first mount.\n * Focus will also be triggered if the value changes from false to true.\n * @default false\n */\n autoFocus: PropTypes.bool,\n /**\n * The content of the component if a `ListItemSecondaryAction` is used it must\n * be the last child.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, compact vertical padding designed for keyboard and mouse input is used.\n * The prop defaults to the value inherited from the parent List component.\n * @default false\n */\n dense: PropTypes.bool,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the left and right padding is removed.\n * @default false\n */\n disableGutters: PropTypes.bool,\n /**\n * If `true`, a 1px light border is added to the bottom of the list item.\n * @default false\n */\n divider: PropTypes.bool,\n /**\n * This prop can help identify which element has keyboard focus.\n * The class name will be applied when the element gains the focus through keyboard interaction.\n * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).\n * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/HEAD/explainer.md).\n * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components\n * if needed.\n */\n focusVisibleClassName: PropTypes.string,\n /**\n * @ignore\n */\n href: PropTypes.string,\n /**\n * Use to apply selected styling.\n * @default false\n */\n selected: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default ListItemButton;","import isMuiElement from '@mui/utils/isMuiElement';\nexport default isMuiElement;","import * as React from 'react';\nexport default function isMuiElement(element, muiNames) {\n var _muiName, _element$type;\n return /*#__PURE__*/React.isValidElement(element) && muiNames.indexOf( // For server components `muiName` is avaialble in element.type._payload.value.muiName\n // relevant info - https://github.com/facebook/react/blob/2807d781a08db8e9873687fccc25c0f12b4fb3d4/packages/react/src/ReactLazy.js#L45\n // eslint-disable-next-line no-underscore-dangle\n (_muiName = element.type.muiName) != null ? _muiName : (_element$type = element.type) == null || (_element$type = _element$type._payload) == null || (_element$type = _element$type.value) == null ? void 0 : _element$type.muiName) !== -1;\n}","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getListItemUtilityClass(slot) {\n return generateUtilityClass('MuiListItem', slot);\n}\nconst listItemClasses = generateUtilityClasses('MuiListItem', ['root', 'container', 'focusVisible', 'dense', 'alignItemsFlexStart', 'disabled', 'divider', 'gutters', 'padding', 'button', 'secondaryAction', 'selected']);\nexport default listItemClasses;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getListItemSecondaryActionClassesUtilityClass(slot) {\n return generateUtilityClass('MuiListItemSecondaryAction', slot);\n}\nconst listItemSecondaryActionClasses = generateUtilityClasses('MuiListItemSecondaryAction', ['root', 'disableGutters']);\nexport default listItemSecondaryActionClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport ListContext from '../List/ListContext';\nimport { getListItemSecondaryActionClassesUtilityClass } from './listItemSecondaryActionClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n disableGutters,\n classes\n } = ownerState;\n const slots = {\n root: ['root', disableGutters && 'disableGutters']\n };\n return composeClasses(slots, getListItemSecondaryActionClassesUtilityClass, classes);\n};\nconst ListItemSecondaryActionRoot = styled('div', {\n name: 'MuiListItemSecondaryAction',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.disableGutters && styles.disableGutters];\n }\n})(({\n ownerState\n}) => _extends({\n position: 'absolute',\n right: 16,\n top: '50%',\n transform: 'translateY(-50%)'\n}, ownerState.disableGutters && {\n right: 0\n}));\n\n/**\n * Must be used as the last child of ListItem to function properly.\n */\nconst ListItemSecondaryAction = /*#__PURE__*/React.forwardRef(function ListItemSecondaryAction(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiListItemSecondaryAction'\n });\n const {\n className\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const context = React.useContext(ListContext);\n const ownerState = _extends({}, props, {\n disableGutters: context.disableGutters\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(ListItemSecondaryActionRoot, _extends({\n className: clsx(classes.root, className),\n ownerState: ownerState,\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? ListItemSecondaryAction.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component, normally an `IconButton` or selection control.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nListItemSecondaryAction.muiName = 'ListItemSecondaryAction';\nexport default ListItemSecondaryAction;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\"],\n _excluded2 = [\"alignItems\", \"autoFocus\", \"button\", \"children\", \"className\", \"component\", \"components\", \"componentsProps\", \"ContainerComponent\", \"ContainerProps\", \"dense\", \"disabled\", \"disableGutters\", \"disablePadding\", \"divider\", \"focusVisibleClassName\", \"secondaryAction\", \"selected\", \"slotProps\", \"slots\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport elementTypeAcceptingRef from '@mui/utils/elementTypeAcceptingRef';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport { alpha } from '@mui/system/colorManipulator';\nimport isHostComponent from '@mui/utils/isHostComponent';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport ButtonBase from '../ButtonBase';\nimport isMuiElement from '../utils/isMuiElement';\nimport useEnhancedEffect from '../utils/useEnhancedEffect';\nimport useForkRef from '../utils/useForkRef';\nimport ListContext from '../List/ListContext';\nimport listItemClasses, { getListItemUtilityClass } from './listItemClasses';\nimport { listItemButtonClasses } from '../ListItemButton';\nimport ListItemSecondaryAction from '../ListItemSecondaryAction';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nexport const overridesResolver = (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.dense && styles.dense, ownerState.alignItems === 'flex-start' && styles.alignItemsFlexStart, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters, !ownerState.disablePadding && styles.padding, ownerState.button && styles.button, ownerState.hasSecondaryAction && styles.secondaryAction];\n};\nconst useUtilityClasses = ownerState => {\n const {\n alignItems,\n button,\n classes,\n dense,\n disabled,\n disableGutters,\n disablePadding,\n divider,\n hasSecondaryAction,\n selected\n } = ownerState;\n const slots = {\n root: ['root', dense && 'dense', !disableGutters && 'gutters', !disablePadding && 'padding', divider && 'divider', disabled && 'disabled', button && 'button', alignItems === 'flex-start' && 'alignItemsFlexStart', hasSecondaryAction && 'secondaryAction', selected && 'selected'],\n container: ['container']\n };\n return composeClasses(slots, getListItemUtilityClass, classes);\n};\nexport const ListItemRoot = styled('div', {\n name: 'MuiListItem',\n slot: 'Root',\n overridesResolver\n})(({\n theme,\n ownerState\n}) => _extends({\n display: 'flex',\n justifyContent: 'flex-start',\n alignItems: 'center',\n position: 'relative',\n textDecoration: 'none',\n width: '100%',\n boxSizing: 'border-box',\n textAlign: 'left'\n}, !ownerState.disablePadding && _extends({\n paddingTop: 8,\n paddingBottom: 8\n}, ownerState.dense && {\n paddingTop: 4,\n paddingBottom: 4\n}, !ownerState.disableGutters && {\n paddingLeft: 16,\n paddingRight: 16\n}, !!ownerState.secondaryAction && {\n // Add some space to avoid collision as `ListItemSecondaryAction`\n // is absolutely positioned.\n paddingRight: 48\n}), !!ownerState.secondaryAction && {\n [`& > .${listItemButtonClasses.root}`]: {\n paddingRight: 48\n }\n}, {\n [`&.${listItemClasses.focusVisible}`]: {\n backgroundColor: (theme.vars || theme).palette.action.focus\n },\n [`&.${listItemClasses.selected}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),\n [`&.${listItemClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)\n }\n },\n [`&.${listItemClasses.disabled}`]: {\n opacity: (theme.vars || theme).palette.action.disabledOpacity\n }\n}, ownerState.alignItems === 'flex-start' && {\n alignItems: 'flex-start'\n}, ownerState.divider && {\n borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,\n backgroundClip: 'padding-box'\n}, ownerState.button && {\n transition: theme.transitions.create('background-color', {\n duration: theme.transitions.duration.shortest\n }),\n '&:hover': {\n textDecoration: 'none',\n backgroundColor: (theme.vars || theme).palette.action.hover,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n },\n [`&.${listItemClasses.selected}:hover`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)\n }\n }\n}, ownerState.hasSecondaryAction && {\n // Add some space to avoid collision as `ListItemSecondaryAction`\n // is absolutely positioned.\n paddingRight: 48\n}));\nconst ListItemContainer = styled('li', {\n name: 'MuiListItem',\n slot: 'Container',\n overridesResolver: (props, styles) => styles.container\n})({\n position: 'relative'\n});\n\n/**\n * Uses an additional container component if `ListItemSecondaryAction` is the last child.\n */\nconst ListItem = /*#__PURE__*/React.forwardRef(function ListItem(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiListItem'\n });\n const {\n alignItems = 'center',\n autoFocus = false,\n button = false,\n children: childrenProp,\n className,\n component: componentProp,\n components = {},\n componentsProps = {},\n ContainerComponent = 'li',\n ContainerProps: {\n className: ContainerClassName\n } = {},\n dense = false,\n disabled = false,\n disableGutters = false,\n disablePadding = false,\n divider = false,\n focusVisibleClassName,\n secondaryAction,\n selected = false,\n slotProps = {},\n slots = {}\n } = props,\n ContainerProps = _objectWithoutPropertiesLoose(props.ContainerProps, _excluded),\n other = _objectWithoutPropertiesLoose(props, _excluded2);\n const context = React.useContext(ListContext);\n const childContext = React.useMemo(() => ({\n dense: dense || context.dense || false,\n alignItems,\n disableGutters\n }), [alignItems, context.dense, dense, disableGutters]);\n const listItemRef = React.useRef(null);\n useEnhancedEffect(() => {\n if (autoFocus) {\n if (listItemRef.current) {\n listItemRef.current.focus();\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('MUI: Unable to set focus to a ListItem whose component has not been rendered.');\n }\n }\n }, [autoFocus]);\n const children = React.Children.toArray(childrenProp);\n\n // v4 implementation, deprecated in v5, will be removed in v6\n const hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);\n const ownerState = _extends({}, props, {\n alignItems,\n autoFocus,\n button,\n dense: childContext.dense,\n disabled,\n disableGutters,\n disablePadding,\n divider,\n hasSecondaryAction,\n selected\n });\n const classes = useUtilityClasses(ownerState);\n const handleRef = useForkRef(listItemRef, ref);\n const Root = slots.root || components.Root || ListItemRoot;\n const rootProps = slotProps.root || componentsProps.root || {};\n const componentProps = _extends({\n className: clsx(classes.root, rootProps.className, className),\n disabled\n }, other);\n let Component = componentProp || 'li';\n if (button) {\n componentProps.component = componentProp || 'div';\n componentProps.focusVisibleClassName = clsx(listItemClasses.focusVisible, focusVisibleClassName);\n Component = ButtonBase;\n }\n\n // v4 implementation, deprecated in v5, will be removed in v6\n if (hasSecondaryAction) {\n // Use div by default.\n Component = !componentProps.component && !componentProp ? 'div' : Component;\n\n // Avoid nesting of li > li.\n if (ContainerComponent === 'li') {\n if (Component === 'li') {\n Component = 'div';\n } else if (componentProps.component === 'li') {\n componentProps.component = 'div';\n }\n }\n return /*#__PURE__*/_jsx(ListContext.Provider, {\n value: childContext,\n children: /*#__PURE__*/_jsxs(ListItemContainer, _extends({\n as: ContainerComponent,\n className: clsx(classes.container, ContainerClassName),\n ref: handleRef,\n ownerState: ownerState\n }, ContainerProps, {\n children: [/*#__PURE__*/_jsx(Root, _extends({}, rootProps, !isHostComponent(Root) && {\n as: Component,\n ownerState: _extends({}, ownerState, rootProps.ownerState)\n }, componentProps, {\n children: children\n })), children.pop()]\n }))\n });\n }\n return /*#__PURE__*/_jsx(ListContext.Provider, {\n value: childContext,\n children: /*#__PURE__*/_jsxs(Root, _extends({}, rootProps, {\n as: Component,\n ref: handleRef\n }, !isHostComponent(Root) && {\n ownerState: _extends({}, ownerState, rootProps.ownerState)\n }, componentProps, {\n children: [children, secondaryAction && /*#__PURE__*/_jsx(ListItemSecondaryAction, {\n children: secondaryAction\n })]\n }))\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? ListItem.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Defines the `align-items` style property.\n * @default 'center'\n */\n alignItems: PropTypes.oneOf(['center', 'flex-start']),\n /**\n * If `true`, the list item is focused during the first mount.\n * Focus will also be triggered if the value changes from false to true.\n * @default false\n * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead\n */\n autoFocus: PropTypes.bool,\n /**\n * If `true`, the list item is a button (using `ButtonBase`). Props intended\n * for `ButtonBase` can then be applied to `ListItem`.\n * @default false\n * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead\n */\n button: PropTypes.bool,\n /**\n * The content of the component if a `ListItemSecondaryAction` is used it must\n * be the last child.\n */\n children: chainPropTypes(PropTypes.node, props => {\n const children = React.Children.toArray(props.children);\n\n // React.Children.toArray(props.children).findLastIndex(isListItemSecondaryAction)\n let secondaryActionIndex = -1;\n for (let i = children.length - 1; i >= 0; i -= 1) {\n const child = children[i];\n if (isMuiElement(child, ['ListItemSecondaryAction'])) {\n secondaryActionIndex = i;\n break;\n }\n }\n\n // is ListItemSecondaryAction the last child of ListItem\n if (secondaryActionIndex !== -1 && secondaryActionIndex !== children.length - 1) {\n return new Error('MUI: You used an element after ListItemSecondaryAction. ' + 'For ListItem to detect that it has a secondary action ' + 'you must pass it as the last child to ListItem.');\n }\n return null;\n }),\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The components used for each slot inside.\n *\n * This prop is an alias for the `slots` prop.\n * It's recommended to use the `slots` prop instead.\n *\n * @default {}\n */\n components: PropTypes.shape({\n Root: PropTypes.elementType\n }),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * This prop is an alias for the `slotProps` prop.\n * It's recommended to use the `slotProps` prop instead, as `componentsProps` will be deprecated in the future.\n *\n * @default {}\n */\n componentsProps: PropTypes.shape({\n root: PropTypes.object\n }),\n /**\n * The container component used when a `ListItemSecondaryAction` is the last child.\n * @default 'li'\n * @deprecated\n */\n ContainerComponent: elementTypeAcceptingRef,\n /**\n * Props applied to the container component if used.\n * @default {}\n * @deprecated\n */\n ContainerProps: PropTypes.object,\n /**\n * If `true`, compact vertical padding designed for keyboard and mouse input is used.\n * The prop defaults to the value inherited from the parent List component.\n * @default false\n */\n dense: PropTypes.bool,\n /**\n * If `true`, the component is disabled.\n * @default false\n * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the left and right padding is removed.\n * @default false\n */\n disableGutters: PropTypes.bool,\n /**\n * If `true`, all padding is removed.\n * @default false\n */\n disablePadding: PropTypes.bool,\n /**\n * If `true`, a 1px light border is added to the bottom of the list item.\n * @default false\n */\n divider: PropTypes.bool,\n /**\n * @ignore\n */\n focusVisibleClassName: PropTypes.string,\n /**\n * The element to display at the end of ListItem.\n */\n secondaryAction: PropTypes.node,\n /**\n * Use to apply selected styling.\n * @default false\n * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead\n */\n selected: PropTypes.bool,\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.\n *\n * @default {}\n */\n slotProps: PropTypes.shape({\n root: PropTypes.object\n }),\n /**\n * The components used for each slot inside.\n *\n * This prop is an alias for the `components` prop, which will be deprecated in the future.\n *\n * @default {}\n */\n slots: PropTypes.shape({\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default ListItem;","import type { Theme } from '@mui/material';\nimport { alpha, decomposeColor, recomposeColor } from '@mui/material';\n\nexport const getContrastAlphaColor = (theme: Theme, value: number) =>\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, value)\n : alpha(theme.palette.common.white, value);\n\nexport const getWarningBackgroundColor = (theme: Theme) =>\n theme.palette.mode === 'light'\n ? alpha(theme.palette.warning.main, 0.32)\n : alpha(theme.palette.warning.main, 0.16);\n\nexport const getInfoBackgroundColor = (theme: Theme) =>\n theme.palette.mode === 'light'\n ? alpha(theme.palette.info.main, 0.12)\n : alpha(theme.palette.info.main, 0.16);\n\n/**\n * https://github.com/mui/material-ui/blob/next/packages/mui-system/src/colorManipulator/colorManipulator.js\n * Blend a transparent overlay color with a background color, resulting in a single\n * RGB color.\n * Remove in favor of MUI one once the next major version is released.\n * @param {string} background - CSS color\n * @param {string} overlay - CSS color\n * @param {number} opacity - Opacity multiplier in the range 0 - 1\n * @param {number} [gamma=1.0] - Gamma correction factor. For gamma-correct blending, 2.2 is usual.\n */\nexport function blend(\n background: string,\n overlay: string,\n opacity: number,\n gamma: number = 1.0,\n) {\n const blendChannel = (b: number, o: number) =>\n Math.round(\n (b ** (1 / gamma) * (1 - opacity) + o ** (1 / gamma) * opacity) ** gamma,\n );\n\n const backgroundColor = decomposeColor(background);\n const overlayColor = decomposeColor(overlay);\n\n const rgb: [number, number, number] = [\n blendChannel(backgroundColor.values[0], overlayColor.values[0]),\n blendChannel(backgroundColor.values[1], overlayColor.values[1]),\n blendChannel(backgroundColor.values[2], overlayColor.values[2]),\n ];\n\n return recomposeColor({\n type: 'rgb',\n values: rgb,\n });\n}\n","import {\n Button,\n ListItem as MuiListItem,\n ListItemButton as MuiListItemButton,\n listItemSecondaryActionClasses,\n styled,\n} from '@mui/material';\nimport { getContrastAlphaColor } from '../../utils/colors.js';\n\nexport const ListItemButton = styled(MuiListItemButton)(({ theme }) => ({\n borderRadius: theme.shape.borderRadius,\n paddingLeft: theme.spacing(1.5),\n paddingRight: theme.spacing(1.5),\n height: 64,\n '&:hover': {\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n },\n}));\n\nexport const ListItem = styled(MuiListItem, {\n shouldForwardProp: (prop) => prop !== 'disableRipple',\n})(({ theme }) => ({\n padding: theme.spacing(0, 1.5),\n [`.${listItemSecondaryActionClasses.root}`]: {\n right: theme.spacing(3),\n },\n '&:hover': {\n cursor: 'pointer',\n },\n}));\n\nexport const ShowAllButton = styled(Button)(({ theme }) => ({\n background: 'none',\n '&:hover': {\n background: 'none',\n },\n padding: theme.spacing(0.75, 2),\n fontSize: '0.875rem',\n}));\n","import { ArrowForward, ErrorRounded, InfoRounded } from '@mui/icons-material';\nimport { ListItemAvatar, ListItemText, Typography } from '@mui/material';\nimport { useNavigate } from 'react-router-dom';\nimport { useProcessMessage } from '../../hooks/useProcessMessage.js';\nimport { useRouteExecution } from '../../hooks/useRouteExecution.js';\nimport { RouteExecutionStatus } from '../../stores/routes/types.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { TokenAvatarGroup } from '../Avatar/Avatar.style.js';\nimport { TokenAvatar } from '../Avatar/TokenAvatar.js';\nimport { StepTimer } from '../Step/StepTimer.js';\nimport { ListItem, ListItemButton } from './ActiveTransactions.style.js';\n\nexport const ActiveTransactionItem: React.FC<{\n routeId: string;\n dense?: boolean;\n}> = ({ routeId, dense }) => {\n const navigate = useNavigate();\n const { route, status } = useRouteExecution({\n routeId,\n executeInBackground: true,\n });\n\n const lastActiveStep = route?.steps.findLast((step) => step.execution);\n const lastActiveProcess = lastActiveStep?.execution?.process.at(-1);\n\n const { title } = useProcessMessage(lastActiveStep, lastActiveProcess);\n\n if (!route || !lastActiveStep) {\n return null;\n }\n\n const handleClick = () => {\n navigate(navigationRoutes.transactionExecution, { state: { routeId } });\n };\n\n const getStatusComponent = () => {\n switch (lastActiveProcess?.status) {\n case 'ACTION_REQUIRED':\n return ;\n case 'FAILED':\n return ;\n default:\n return (\n \n \n \n );\n }\n };\n\n const ListItemComponent = dense ? ListItem : ListItemButton;\n\n return (\n \n \n \n \n \n \n \n \n {route.fromToken.symbol}\n \n {route.toToken.symbol}\n \n }\n secondary={\n status !== RouteExecutionStatus.Done ? (\n \n {title}\n \n ) : null\n }\n />\n {getStatusComponent()}\n \n );\n};\n","'use client';\n\n/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { exactProp, elementAcceptingRef, unstable_useForkRef as useForkRef, unstable_ownerDocument as ownerDocument } from '@mui/utils';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\n// Inspired by https://github.com/focus-trap/tabbable\nconst candidatesSelector = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable=\"false\"])'].join(',');\nfunction getTabIndex(node) {\n const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10);\n if (!Number.isNaN(tabindexAttr)) {\n return tabindexAttr;\n }\n\n // Browsers do not return `tabIndex` correctly for contentEditable nodes;\n // https://bugs.chromium.org/p/chromium/issues/detail?id=661108&q=contenteditable%20tabindex&can=2\n // so if they don't have a tabindex attribute specifically set, assume it's 0.\n // in Chrome,
,
(8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase()\n const hash = keccak256(stringToBytes(hexAddress), 'bytes')\n\n const address = (\n chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress\n ).split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase()\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase()\n }\n }\n\n const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import { keccak_256 } from '@noble/hashes/sha3'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Keccak256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Keccak256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function keccak256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Keccak256Hash {\n const to = to_ || 'hex'\n const bytes = keccak_256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Keccak256Hash\n return toHex(bytes) as Keccak256Hash\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\n}\n","function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n// copied from utils\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType;\n\nexport function wrapConstructor>(hashCons: () => Hash) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => Hash\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nexport class SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn: (arg: T, ...args: O) => R) {\n const map = new WeakMap();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp: IField, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f: IField, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f: IField, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv(f: IField, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\nexport function FpLegendre(order: bigint) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f: IField, x: T): T => f.pow(x, legendreConst);\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f: IField) {\n const legendre = FpLegendre(f.ORDER);\n return (x: T): boolean => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial> = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper = (i: T[]) => T[];\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF>(c: GroupConstructor, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W: number) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W: number) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper): { p: T; f: T } {\n const W: number = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n\n setWindowSize(P: T, W: number) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger>(\n c: GroupConstructor,\n field: IField,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof (c as any))) throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic(curve: BasicCurve & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport {\n AffinePoint,\n BasicCurve,\n Group,\n GroupConstructor,\n validateBasic,\n wNAF,\n pippenger,\n} from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex, memoized, abool } from './utils.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio √(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool('phflag', phflag);\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n\n function assertPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]) {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { AffinePoint, Group } from './abstract/curve.js';\nimport { CurveFn, ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xmd, htfBasicOpts } from './abstract/hash-to-curve.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n",null,null,null,null,null,null,"/**\n * WebSocket implements a browser-side WebSocket specification.\n * @module Client\n */\n\n\"use strict\"\n\nimport { EventEmitter } from \"eventemitter3\"\n\nimport {\n BrowserWebSocketType,\n NodeWebSocketType,\n IWSClientAdditionalOptions,\n} from \"./client.types.js\"\n\nclass WebSocketBrowserImpl extends EventEmitter\n{\n socket: BrowserWebSocketType\n\n /** Instantiate a WebSocket class\n * @constructor\n * @param {String} address - url to a websocket server\n * @param {(Object)} options - websocket options\n * @param {(String|Array)} protocols - a list of protocols\n * @return {WebSocketBrowserImpl} - returns a WebSocket instance\n */\n constructor(address: string, options: {}, protocols?: string | string[])\n {\n super()\n\n this.socket = new window.WebSocket(address, protocols)\n\n this.socket.onopen = () => this.emit(\"open\")\n this.socket.onmessage = (event) => this.emit(\"message\", event.data)\n this.socket.onerror = (error) => this.emit(\"error\", error)\n this.socket.onclose = (event) =>\n {\n this.emit(\"close\", event.code, event.reason)\n }\n }\n\n /**\n * Sends data through a websocket connection\n * @method\n * @param {(String|Object)} data - data to be sent via websocket\n * @param {Object} optionsOrCallback - ws options\n * @param {Function} callback - a callback called once the data is sent\n * @return {Undefined}\n */\n send(\n data: Parameters[0],\n optionsOrCallback: (\n error?: Error\n ) => void | Parameters[1],\n callback?: () => void\n )\n {\n const cb = callback || optionsOrCallback\n\n try\n {\n this.socket.send(data)\n cb()\n }\n catch (error)\n {\n cb(error)\n }\n }\n\n /**\n * Closes an underlying socket\n * @method\n * @param {Number} code - status code explaining why the connection is being closed\n * @param {String} reason - a description why the connection is closing\n * @return {Undefined}\n * @throws {Error}\n */\n close(code?: number, reason?: string)\n {\n this.socket.close(code, reason)\n }\n\n addEventListener(\n type: K,\n listener: (ev: WebSocketEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions\n ): void\n {\n this.socket.addEventListener(type, listener, options)\n }\n}\n\n/**\n * factory method for common WebSocket instance\n * @method\n * @param {String} address - url to a websocket server\n * @param {(Object)} options - websocket options\n * @return {Undefined}\n */\nexport function WebSocket(\n address: string,\n options: IWSClientAdditionalOptions\n)\n{\n return new WebSocketBrowserImpl(address, options)\n}\n","/**\n * \"Client\" wraps \"ws\" or a browser-implemented \"WebSocket\" library\n * according to the environment providing JSON RPC 2.0 support on top.\n * @module Client\n */\n\n\"use strict\"\n\nimport NodeWebSocket from \"ws\"\nimport { EventEmitter } from \"eventemitter3\"\nimport {\n ICommonWebSocket,\n IWSClientAdditionalOptions,\n NodeWebSocketType,\n ICommonWebSocketFactory,\n} from \"./client/client.types.js\"\n\nimport { DataPack, DefaultDataPack } from \"./utils.js\"\n\ninterface IQueueElement {\n promise: [\n Parameters[0]>[0],\n Parameters[0]>[1]\n ];\n timeout?: ReturnType;\n}\n\nexport interface IQueue {\n [x: number]: IQueueElement;\n}\n\nexport interface IWSRequestParams {\n [x: string]: any;\n [x: number]: any;\n}\n\nexport class CommonClient extends EventEmitter\n{\n private address: string\n private rpc_id: number\n private queue: IQueue\n private options: IWSClientAdditionalOptions & NodeWebSocket.ClientOptions\n private autoconnect: boolean\n private ready: boolean\n private reconnect: boolean\n private reconnect_timer_id: NodeJS.Timeout\n private reconnect_interval: number\n private max_reconnects: number\n private rest_options: IWSClientAdditionalOptions &\n NodeWebSocket.ClientOptions\n private current_reconnects: number\n private generate_request_id: (\n method: string,\n params: object | Array\n ) => number\n private socket: ICommonWebSocket\n private webSocketFactory: ICommonWebSocketFactory\n private dataPack: DataPack\n\n /**\n * Instantiate a Client class.\n * @constructor\n * @param {webSocketFactory} webSocketFactory - factory method for WebSocket\n * @param {String} address - url to a websocket server\n * @param {Object} options - ws options object with reconnect parameters\n * @param {Function} generate_request_id - custom generation request Id\n * @param {DataPack} dataPack - data pack contains encoder and decoder\n * @return {CommonClient}\n */\n constructor(\n webSocketFactory: ICommonWebSocketFactory,\n address = \"ws://localhost:8080\",\n {\n autoconnect = true,\n reconnect = true,\n reconnect_interval = 1000,\n max_reconnects = 5,\n ...rest_options\n } = {},\n generate_request_id?: (\n method: string,\n params: object | Array\n ) => number,\n dataPack?: DataPack\n )\n {\n super()\n\n this.webSocketFactory = webSocketFactory\n\n this.queue = {}\n this.rpc_id = 0\n\n this.address = address\n this.autoconnect = autoconnect\n this.ready = false\n this.reconnect = reconnect\n this.reconnect_timer_id = undefined\n this.reconnect_interval = reconnect_interval\n this.max_reconnects = max_reconnects\n this.rest_options = rest_options\n this.current_reconnects = 0\n this.generate_request_id = generate_request_id || (() => ++this.rpc_id)\n\n if (!dataPack) this.dataPack = new DefaultDataPack()\n else this.dataPack = dataPack\n\n if (this.autoconnect)\n this._connect(this.address, {\n autoconnect: this.autoconnect,\n reconnect: this.reconnect,\n reconnect_interval: this.reconnect_interval,\n max_reconnects: this.max_reconnects,\n ...this.rest_options,\n })\n }\n\n /**\n * Connects to a defined server if not connected already.\n * @method\n * @return {Undefined}\n */\n connect()\n {\n if (this.socket) return\n\n this._connect(this.address, {\n autoconnect: this.autoconnect,\n reconnect: this.reconnect,\n reconnect_interval: this.reconnect_interval,\n max_reconnects: this.max_reconnects,\n ...this.rest_options,\n })\n }\n\n /**\n * Calls a registered RPC method on server.\n * @method\n * @param {String} method - RPC method name\n * @param {Object|Array} params - optional method parameters\n * @param {Number} timeout - RPC reply timeout value\n * @param {Object} ws_opts - options passed to ws\n * @return {Promise}\n */\n call(\n method: string,\n params?: IWSRequestParams,\n timeout?: number,\n ws_opts?: Parameters[1]\n )\n {\n if (!ws_opts && \"object\" === typeof timeout)\n {\n ws_opts = timeout\n timeout = null\n }\n\n return new Promise((resolve, reject) =>\n {\n if (!this.ready) return reject(new Error(\"socket not ready\"))\n\n const rpc_id = this.generate_request_id(method, params)\n\n const message = {\n jsonrpc: \"2.0\",\n method: method,\n params: params || undefined,\n id: rpc_id,\n }\n\n this.socket.send(this.dataPack.encode(message), ws_opts, (error) =>\n {\n if (error) return reject(error)\n\n this.queue[rpc_id] = { promise: [resolve, reject] }\n\n if (timeout)\n {\n this.queue[rpc_id].timeout = setTimeout(() =>\n {\n delete this.queue[rpc_id]\n reject(new Error(\"reply timeout\"))\n }, timeout)\n }\n })\n })\n }\n\n /**\n * Logins with the other side of the connection.\n * @method\n * @param {Object} params - Login credentials object\n * @return {Promise}\n */\n async login(params: IWSRequestParams)\n {\n const resp = await this.call(\"rpc.login\", params)\n\n if (!resp) throw new Error(\"authentication failed\")\n\n return resp\n }\n\n /**\n * Fetches a list of client's methods registered on server.\n * @method\n * @return {Array}\n */\n async listMethods()\n {\n return await this.call(\"__listMethods\")\n }\n\n /**\n * Sends a JSON-RPC 2.0 notification to server.\n * @method\n * @param {String} method - RPC method name\n * @param {Object} params - optional method parameters\n * @return {Promise}\n */\n notify(method: string, params?: IWSRequestParams)\n {\n return new Promise((resolve, reject) =>\n {\n if (!this.ready) return reject(new Error(\"socket not ready\"))\n\n const message = {\n jsonrpc: \"2.0\",\n method: method,\n params,\n }\n\n this.socket.send(this.dataPack.encode(message), (error) =>\n {\n if (error) return reject(error)\n\n resolve()\n })\n })\n }\n\n /**\n * Subscribes for a defined event.\n * @method\n * @param {String|Array} event - event name\n * @return {Undefined}\n * @throws {Error}\n */\n async subscribe(event: string | Array)\n {\n if (typeof event === \"string\") event = [event]\n\n const result = await this.call(\"rpc.on\", event)\n\n if (typeof event === \"string\" && result[event] !== \"ok\")\n throw new Error(\n \"Failed subscribing to an event '\" + event + \"' with: \" + result[event]\n )\n\n return result\n }\n\n /**\n * Unsubscribes from a defined event.\n * @method\n * @param {String|Array} event - event name\n * @return {Undefined}\n * @throws {Error}\n */\n async unsubscribe(event: string | Array)\n {\n if (typeof event === \"string\") event = [event]\n\n const result = await this.call(\"rpc.off\", event)\n\n if (typeof event === \"string\" && result[event] !== \"ok\")\n throw new Error(\"Failed unsubscribing from an event with: \" + result)\n\n return result\n }\n\n /**\n * Closes a WebSocket connection gracefully.\n * @method\n * @param {Number} code - socket close code\n * @param {String} data - optional data to be sent before closing\n * @return {Undefined}\n */\n close(code?: number, data?: string)\n {\n this.socket.close(code || 1000, data)\n }\n\n /**\n * Enable / disable automatic reconnection.\n * @method\n * @param {Boolean} reconnect - enable / disable reconnection\n * @return {Undefined}\n */\n setAutoReconnect(reconnect: boolean)\n {\n this.reconnect = reconnect\n }\n\n /**\n * Set the interval between reconnection attempts.\n * @method\n * @param {Number} interval - reconnection interval in milliseconds\n * @return {Undefined}\n */\n setReconnectInterval(interval: number)\n {\n this.reconnect_interval = interval\n }\n\n /**\n * Set the maximum number of reconnection attempts.\n * @method\n * @param {Number} max_reconnects - maximum reconnection attempts\n * @return {Undefined}\n */\n setMaxReconnects(max_reconnects: number)\n {\n this.max_reconnects = max_reconnects\n }\n\n /**\n * Connection/Message handler.\n * @method\n * @private\n * @param {String} address - WebSocket API address\n * @param {Object} options - ws options object\n * @return {Undefined}\n */\n private _connect(\n address: string,\n options: IWSClientAdditionalOptions & NodeWebSocket.ClientOptions\n )\n {\n clearTimeout(this.reconnect_timer_id)\n this.socket = this.webSocketFactory(address, options)\n\n this.socket.addEventListener(\"open\", () =>\n {\n this.ready = true\n this.emit(\"open\")\n this.current_reconnects = 0\n })\n\n this.socket.addEventListener(\"message\", ({ data: message }) =>\n {\n if (message instanceof ArrayBuffer)\n message = Buffer.from(message).toString()\n\n try\n {\n message = this.dataPack.decode(message)\n }\n catch (error)\n {\n return\n }\n\n // check if any listeners are attached and forward event\n if (message.notification && this.listeners(message.notification).length)\n {\n if (!Object.keys(message.params).length)\n return this.emit(message.notification)\n\n const args = [message.notification]\n\n if (message.params.constructor === Object) args.push(message.params)\n // using for-loop instead of unshift/spread because performance is better\n else\n for (let i = 0; i < message.params.length; i++)\n args.push(message.params[i])\n\n // run as microtask so that pending queue messages are resolved first\n // eslint-disable-next-line prefer-spread\n return Promise.resolve().then(() =>\n {\n // eslint-disable-next-line prefer-spread\n this.emit.apply(this, args)\n })\n }\n\n if (!this.queue[message.id])\n {\n // general JSON RPC 2.0 events\n if (message.method)\n {\n // run as microtask so that pending queue messages are resolved first\n return Promise.resolve().then(() =>\n {\n this.emit(message.method, message?.params)\n })\n }\n\n return\n }\n\n // reject early since server's response is invalid\n if (\"error\" in message === \"result\" in message)\n this.queue[message.id].promise[1](\n new Error(\n \"Server response malformed. Response must include either \\\"result\\\"\" +\n \" or \\\"error\\\", but not both.\"\n )\n )\n\n if (this.queue[message.id].timeout)\n clearTimeout(this.queue[message.id].timeout)\n\n if (message.error) this.queue[message.id].promise[1](message.error)\n else this.queue[message.id].promise[0](message.result)\n\n delete this.queue[message.id]\n })\n\n this.socket.addEventListener(\"error\", (error) => this.emit(\"error\", error))\n\n this.socket.addEventListener(\"close\", ({ code, reason }) =>\n {\n if (this.ready)\n // Delay close event until internal state is updated\n setTimeout(() => this.emit(\"close\", code, reason), 0)\n\n this.ready = false\n this.socket = undefined\n\n if (code === 1000) return\n\n this.current_reconnects++\n\n if (\n this.reconnect &&\n (this.max_reconnects > this.current_reconnects ||\n this.max_reconnects === 0)\n )\n this.reconnect_timer_id = setTimeout(\n () => this._connect(address, options),\n this.reconnect_interval\n )\n })\n }\n}\n","\"use strict\"\n\nexport interface DataPack<\n T,\n R extends string | ArrayBufferLike | Blob | ArrayBufferView\n> {\n encode(value: T): R;\n decode(value: R): T;\n}\n\nexport class DefaultDataPack implements DataPack\n{\n encode(value: Object): string\n {\n return JSON.stringify(value)\n }\n\n decode(value: string): Object\n {\n return JSON.parse(value)\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport {\n AffinePoint,\n BasicCurve,\n Group,\n GroupConstructor,\n validateBasic,\n wNAF,\n pippenger,\n} from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes, memoized, abool } from './utils.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType;\n};\n\ntype Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType extends Group> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType;\n toAffine(iz?: T): AffinePoint;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor extends GroupConstructor> {\n new (x: T, y: T, z: T): ProjPointType;\n fromAffine(p: AffinePoint): ProjPointType;\n fromHex(hex: Hex): ProjPointType;\n fromPrivateKey(privateKey: PrivKey): ProjPointType;\n normalizeZ(points: ProjPointType[]): ProjPointType[];\n msm(points: ProjPointType[], scalars: bigint[]): ProjPointType;\n}\n\nexport type CurvePointsType = BasicWCurve & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts(curve: CurvePointsType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes = {\n CURVE: ReturnType>;\n ProjectivePoint: ProjConstructor;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint) {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected assertion');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints(opts: CurvePointsType): CurvePointsRes {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey) num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]) {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (sc === _1n) return this;\n const { endo } = CURVE;\n if (!endo) return wnaf.unsafeLadder(this, sc);\n\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType;\n\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n throw new Error(\n `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n _sig = Signature.fromCompact(sg);\n }\n } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n } else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n if ((error as Error).message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp: mod.IField, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: mod.IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { CHash } from './abstract/utils.js';\nimport { CurveType, weierstrass } from './abstract/weierstrass.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport {\n inRange,\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n numberToBytesBE,\n} from './abstract/utils.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n","import {ed25519} from '@noble/curves/ed25519';\n\n/**\n * A 64 byte secret key, the first 32 bytes of which is the\n * private scalar and the last 32 bytes is the public key.\n * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/\n */\ntype Ed25519SecretKey = Uint8Array;\n\n/**\n * Ed25519 Keypair\n */\nexport interface Ed25519Keypair {\n publicKey: Uint8Array;\n secretKey: Ed25519SecretKey;\n}\n\nexport const generatePrivateKey = ed25519.utils.randomPrivateKey;\nexport const generateKeypair = (): Ed25519Keypair => {\n const privateScalar = ed25519.utils.randomPrivateKey();\n const publicKey = getPublicKey(privateScalar);\n const secretKey = new Uint8Array(64);\n secretKey.set(privateScalar);\n secretKey.set(publicKey, 32);\n return {\n publicKey,\n secretKey,\n };\n};\nexport const getPublicKey = ed25519.getPublicKey;\nexport function isOnCurve(publicKey: Uint8Array): boolean {\n try {\n ed25519.ExtendedPoint.fromHex(publicKey);\n return true;\n } catch {\n return false;\n }\n}\nexport const sign = (\n message: Parameters[0],\n secretKey: Ed25519SecretKey,\n) => ed25519.sign(message, secretKey.slice(0, 32));\nexport const verify = ed25519.verify;\n","import {Buffer} from 'buffer';\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array): 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","import {Buffer} from 'buffer';\nimport {serialize, deserialize, deserializeUnchecked} from 'borsh';\n\n// Class wrapping a plain object\nexport class Struct {\n constructor(properties: any) {\n Object.assign(this, properties);\n }\n\n encode(): Buffer {\n return Buffer.from(serialize(SOLANA_SCHEMA, this));\n }\n\n static decode(data: Buffer): any {\n return deserialize(SOLANA_SCHEMA, this, data);\n }\n\n static decodeUnchecked(data: Buffer): any {\n return deserializeUnchecked(SOLANA_SCHEMA, this, data);\n }\n}\n\n// Class representing a Rust-compatible enum, since enums are only strings or\n// numbers in pure JS\nexport class Enum extends Struct {\n enum: string = '';\n constructor(properties: any) {\n super(properties);\n if (Object.keys(properties).length !== 1) {\n throw new Error('Enum can only take single value');\n }\n Object.keys(properties).map(key => {\n this.enum = key;\n });\n }\n}\n\nexport const SOLANA_SCHEMA: Map = new Map();\n","import BN from 'bn.js';\nimport bs58 from 'bs58';\nimport {Buffer} from 'buffer';\nimport {sha256} from '@noble/hashes/sha256';\n\nimport {isOnCurve} from './utils/ed25519';\nimport {Struct, SOLANA_SCHEMA} from './utils/borsh-schema';\nimport {toBuffer} from './utils/to-buffer';\n\n/**\n * Maximum length of derived pubkey seed\n */\nexport const MAX_SEED_LENGTH = 32;\n\n/**\n * Size of public key in bytes\n */\nexport const PUBLIC_KEY_LENGTH = 32;\n\n/**\n * Value to be converted into public key\n */\nexport type PublicKeyInitData =\n | number\n | string\n | Uint8Array\n | Array\n | PublicKeyData;\n\n/**\n * JSON object representation of PublicKey class\n */\nexport type PublicKeyData = {\n /** @internal */\n _bn: BN;\n};\n\nfunction isPublicKeyData(value: PublicKeyInitData): value is PublicKeyData {\n return (value as PublicKeyData)._bn !== undefined;\n}\n\n// local counter used by PublicKey.unique()\nlet uniquePublicKeyCounter = 1;\n\n/**\n * A public key\n */\nexport class PublicKey extends Struct {\n /** @internal */\n _bn: BN;\n\n /**\n * Create a new PublicKey object\n * @param value ed25519 public key as buffer or base-58 encoded string\n */\n constructor(value: PublicKeyInitData) {\n super({});\n if (isPublicKeyData(value)) {\n this._bn = value._bn;\n } else {\n if (typeof value === 'string') {\n // assume base 58 encoding by default\n const decoded = bs58.decode(value);\n if (decoded.length != PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n this._bn = new BN(decoded);\n } else {\n this._bn = new BN(value);\n }\n\n if (this._bn.byteLength() > PUBLIC_KEY_LENGTH) {\n throw new Error(`Invalid public key input`);\n }\n }\n }\n\n /**\n * Returns a unique PublicKey for tests and benchmarks using a counter\n */\n static unique(): PublicKey {\n const key = new PublicKey(uniquePublicKeyCounter);\n uniquePublicKeyCounter += 1;\n return new PublicKey(key.toBuffer());\n }\n\n /**\n * Default public key value. The base58-encoded string representation is all ones (as seen below)\n * The underlying BN number is 32 bytes that are all zeros\n */\n static default: PublicKey = new PublicKey('11111111111111111111111111111111');\n\n /**\n * Checks if two publicKeys are equal\n */\n equals(publicKey: PublicKey): boolean {\n return this._bn.eq(publicKey._bn);\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toBase58(): string {\n return bs58.encode(this.toBytes());\n }\n\n toJSON(): string {\n return this.toBase58();\n }\n\n /**\n * Return the byte array representation of the public key in big endian\n */\n toBytes(): Uint8Array {\n const buf = this.toBuffer();\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n\n /**\n * Return the Buffer representation of the public key in big endian\n */\n toBuffer(): Buffer {\n const b = this._bn.toArrayLike(Buffer);\n if (b.length === PUBLIC_KEY_LENGTH) {\n return b;\n }\n\n const zeroPad = Buffer.alloc(32);\n b.copy(zeroPad, 32 - b.length);\n return zeroPad;\n }\n\n get [Symbol.toStringTag](): string {\n return `PublicKey(${this.toString()})`;\n }\n\n /**\n * Return the base-58 representation of the public key\n */\n toString(): string {\n return this.toBase58();\n }\n\n /**\n * Derive a public key from another key, a seed, and a program ID.\n * The program ID will also serve as the owner of the public key, giving\n * it permission to write data to the account.\n */\n /* eslint-disable require-await */\n static async createWithSeed(\n fromPublicKey: PublicKey,\n seed: string,\n programId: PublicKey,\n ): Promise {\n const buffer = Buffer.concat([\n fromPublicKey.toBuffer(),\n Buffer.from(seed),\n programId.toBuffer(),\n ]);\n const publicKeyBytes = sha256(buffer);\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Derive a program address from seeds and a program ID.\n */\n /* eslint-disable require-await */\n static createProgramAddressSync(\n seeds: Array,\n programId: PublicKey,\n ): PublicKey {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([\n buffer,\n programId.toBuffer(),\n Buffer.from('ProgramDerivedAddress'),\n ]);\n const publicKeyBytes = sha256(buffer);\n if (isOnCurve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n return new PublicKey(publicKeyBytes);\n }\n\n /**\n * Async version of createProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link createProgramAddressSync} instead\n */\n /* eslint-disable require-await */\n static async createProgramAddress(\n seeds: Array,\n programId: PublicKey,\n ): Promise {\n return this.createProgramAddressSync(seeds, programId);\n }\n\n /**\n * Find a valid program address\n *\n * Valid program addresses must fall off the ed25519 curve. This function\n * iterates a nonce until it finds one that when combined with the seeds\n * results in a valid program address.\n */\n static findProgramAddressSync(\n seeds: Array,\n programId: PublicKey,\n ): [PublicKey, number] {\n let nonce = 255;\n let address;\n while (nonce != 0) {\n try {\n const seedsWithNonce = seeds.concat(Buffer.from([nonce]));\n address = this.createProgramAddressSync(seedsWithNonce, programId);\n } catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n nonce--;\n continue;\n }\n return [address, nonce];\n }\n throw new Error(`Unable to find a viable program address nonce`);\n }\n\n /**\n * Async version of findProgramAddressSync\n * For backwards compatibility\n *\n * @deprecated Use {@link findProgramAddressSync} instead\n */\n static async findProgramAddress(\n seeds: Array,\n programId: PublicKey,\n ): Promise<[PublicKey, number]> {\n return this.findProgramAddressSync(seeds, programId);\n }\n\n /**\n * Check that a pubkey is on the ed25519 curve.\n */\n static isOnCurve(pubkeyData: PublicKeyInitData): boolean {\n const pubkey = new PublicKey(pubkeyData);\n return isOnCurve(pubkey.toBytes());\n }\n}\n\nSOLANA_SCHEMA.set(PublicKey, {\n kind: 'struct',\n fields: [['_bn', 'u256']],\n});\n","import {PublicKey} from './publickey';\n\nexport const BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey(\n 'BPFLoader1111111111111111111111111111111111',\n);\n","/**\n * Maximum over-the-wire size of a Transaction\n *\n * 1280 is IPv6 minimum MTU\n * 40 bytes is the size of the IPv6 header\n * 8 bytes is the size of the fragment header\n */\nexport const PACKET_DATA_SIZE = 1280 - 40 - 8;\n\nexport const VERSION_PREFIX_MASK = 0x7f;\n\nexport const SIGNATURE_LENGTH_IN_BYTES = 64;\n","export class TransactionExpiredBlockheightExceededError extends Error {\n signature: string;\n\n constructor(signature: string) {\n super(`Signature ${signature} has expired: block height exceeded.`);\n this.signature = signature;\n }\n}\n\nObject.defineProperty(\n TransactionExpiredBlockheightExceededError.prototype,\n 'name',\n {\n value: 'TransactionExpiredBlockheightExceededError',\n },\n);\n\nexport class TransactionExpiredTimeoutError extends Error {\n signature: string;\n\n constructor(signature: string, timeoutSeconds: number) {\n super(\n `Transaction was not confirmed in ${timeoutSeconds.toFixed(\n 2,\n )} seconds. It is ` +\n 'unknown if it succeeded or failed. Check signature ' +\n `${signature} using the Solana Explorer or CLI tools.`,\n );\n this.signature = signature;\n }\n}\n\nObject.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', {\n value: 'TransactionExpiredTimeoutError',\n});\n\nexport class TransactionExpiredNonceInvalidError extends Error {\n signature: string;\n\n constructor(signature: string) {\n super(`Signature ${signature} has expired: the nonce is no longer valid.`);\n this.signature = signature;\n }\n}\n\nObject.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', {\n value: 'TransactionExpiredNonceInvalidError',\n});\n","import {LoadedAddresses} from '../connection';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport {MessageCompiledInstruction} from './index';\n\nexport type AccountKeysFromLookups = LoadedAddresses;\n\nexport class MessageAccountKeys {\n staticAccountKeys: Array;\n accountKeysFromLookups?: AccountKeysFromLookups;\n\n constructor(\n staticAccountKeys: Array,\n accountKeysFromLookups?: AccountKeysFromLookups,\n ) {\n this.staticAccountKeys = staticAccountKeys;\n this.accountKeysFromLookups = accountKeysFromLookups;\n }\n\n keySegments(): Array> {\n const keySegments = [this.staticAccountKeys];\n if (this.accountKeysFromLookups) {\n keySegments.push(this.accountKeysFromLookups.writable);\n keySegments.push(this.accountKeysFromLookups.readonly);\n }\n return keySegments;\n }\n\n get(index: number): PublicKey | undefined {\n for (const keySegment of this.keySegments()) {\n if (index < keySegment.length) {\n return keySegment[index];\n } else {\n index -= keySegment.length;\n }\n }\n return;\n }\n\n get length(): number {\n return this.keySegments().flat().length;\n }\n\n compileInstructions(\n instructions: Array,\n ): Array {\n // Bail early if any account indexes would overflow a u8\n const U8_MAX = 255;\n if (this.length > U8_MAX + 1) {\n throw new Error('Account index overflow encountered during compilation');\n }\n\n const keyIndexMap = new Map();\n this.keySegments()\n .flat()\n .forEach((key, index) => {\n keyIndexMap.set(key.toBase58(), index);\n });\n\n const findKeyIndex = (key: PublicKey) => {\n const keyIndex = keyIndexMap.get(key.toBase58());\n if (keyIndex === undefined)\n throw new Error(\n 'Encountered an unknown instruction account key during compilation',\n );\n return keyIndex;\n };\n\n return instructions.map((instruction): MessageCompiledInstruction => {\n return {\n programIdIndex: findKeyIndex(instruction.programId),\n accountKeyIndexes: instruction.keys.map(meta =>\n findKeyIndex(meta.pubkey),\n ),\n data: instruction.data,\n };\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {VoteAuthorizeWithSeedArgs} from './programs/vote';\n\n/**\n * Layout for a public key\n */\nexport const publicKey = (property: string = 'publicKey') => {\n return BufferLayout.blob(32, property);\n};\n\n/**\n * Layout for a signature\n */\nexport const signature = (property: string = 'signature') => {\n return BufferLayout.blob(64, property);\n};\n\n/**\n * Layout for a 64bit unsigned value\n */\nexport const uint64 = (property: string = 'uint64') => {\n return BufferLayout.blob(8, property);\n};\n\ninterface IRustStringShim\n extends Omit<\n BufferLayout.Structure<\n Readonly<{\n length: number;\n lengthPadding: number;\n chars: Uint8Array;\n }>\n >,\n 'decode' | 'encode' | 'replicate'\n > {\n alloc: (str: string) => number;\n decode: (b: Uint8Array, offset?: number) => string;\n encode: (str: string, b: Uint8Array, offset?: number) => number;\n replicate: (property: string) => this;\n}\n\n/**\n * Layout for a Rust String type\n */\nexport const rustString = (\n property: string = 'string',\n): BufferLayout.Layout => {\n const rsl = BufferLayout.struct<\n Readonly<{\n length?: number;\n lengthPadding?: number;\n chars: Uint8Array;\n }>\n >(\n [\n BufferLayout.u32('length'),\n BufferLayout.u32('lengthPadding'),\n BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars'),\n ],\n property,\n );\n const _decode = rsl.decode.bind(rsl);\n const _encode = rsl.encode.bind(rsl);\n\n const rslShim = rsl as unknown as IRustStringShim;\n\n rslShim.decode = (b: Uint8Array, offset?: number) => {\n const data = _decode(b, offset);\n return data['chars'].toString();\n };\n\n rslShim.encode = (str: string, b: Uint8Array, offset?: number) => {\n const data = {\n chars: Buffer.from(str, 'utf8'),\n };\n return _encode(data, b, offset);\n };\n\n rslShim.alloc = (str: string) => {\n return (\n BufferLayout.u32().span +\n BufferLayout.u32().span +\n Buffer.from(str, 'utf8').length\n );\n };\n\n return rslShim;\n};\n\n/**\n * Layout for an Authorized object\n */\nexport const authorized = (property: string = 'authorized') => {\n return BufferLayout.struct<\n Readonly<{\n staker: Uint8Array;\n withdrawer: Uint8Array;\n }>\n >([publicKey('staker'), publicKey('withdrawer')], property);\n};\n\n/**\n * Layout for a Lockup object\n */\nexport const lockup = (property: string = 'lockup') => {\n return BufferLayout.struct<\n Readonly<{\n custodian: Uint8Array;\n epoch: number;\n unixTimestamp: number;\n }>\n >(\n [\n BufferLayout.ns64('unixTimestamp'),\n BufferLayout.ns64('epoch'),\n publicKey('custodian'),\n ],\n property,\n );\n};\n\n/**\n * Layout for a VoteInit object\n */\nexport const voteInit = (property: string = 'voteInit') => {\n return BufferLayout.struct<\n Readonly<{\n authorizedVoter: Uint8Array;\n authorizedWithdrawer: Uint8Array;\n commission: number;\n nodePubkey: Uint8Array;\n }>\n >(\n [\n publicKey('nodePubkey'),\n publicKey('authorizedVoter'),\n publicKey('authorizedWithdrawer'),\n BufferLayout.u8('commission'),\n ],\n property,\n );\n};\n\n/**\n * Layout for a VoteAuthorizeWithSeedArgs object\n */\nexport const voteAuthorizeWithSeedArgs = (\n property: string = 'voteAuthorizeWithSeedArgs',\n) => {\n return BufferLayout.struct(\n [\n BufferLayout.u32('voteAuthorizationType'),\n publicKey('currentAuthorityDerivedKeyOwnerPubkey'),\n rustString('currentAuthorityDerivedKeySeed'),\n publicKey('newAuthorized'),\n ],\n property,\n );\n};\n\nexport function getAlloc(type: any, fields: any): number {\n const getItemAlloc = (item: any): number => {\n if (item.span >= 0) {\n return item.span;\n } else if (typeof item.alloc === 'function') {\n return item.alloc(fields[item.property]);\n } else if ('count' in item && 'elementLayout' in item) {\n const field = fields[item.property];\n if (Array.isArray(field)) {\n return field.length * getItemAlloc(item.elementLayout);\n }\n } else if ('fields' in item) {\n // This is a `Structure` whose size needs to be recursively measured.\n return getAlloc({layout: item}, fields[item.property]);\n }\n // Couldn't determine allocated size of layout\n return 0;\n };\n\n let alloc = 0;\n type.layout.fields.forEach((item: any) => {\n alloc += getItemAlloc(item);\n });\n\n return alloc;\n}\n","export function decodeLength(bytes: Array): number {\n let len = 0;\n let size = 0;\n for (;;) {\n let elem = bytes.shift() as number;\n len |= (elem & 0x7f) << (size * 7);\n size += 1;\n if ((elem & 0x80) === 0) {\n break;\n }\n }\n return len;\n}\n\nexport function encodeLength(bytes: Array, len: number) {\n let rem_len = len;\n for (;;) {\n let elem = rem_len & 0x7f;\n rem_len >>= 7;\n if (rem_len == 0) {\n bytes.push(elem);\n break;\n } else {\n elem |= 0x80;\n bytes.push(elem);\n }\n }\n}\n","export default function (\n condition: unknown,\n message?: string,\n): asserts condition {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n}\n","import {MessageHeader, MessageAddressTableLookup} from './index';\nimport {AccountKeysFromLookups} from './account-keys';\nimport {AddressLookupTableAccount} from '../programs';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {PublicKey} from '../publickey';\n\nexport type CompiledKeyMeta = {\n isSigner: boolean;\n isWritable: boolean;\n isInvoked: boolean;\n};\n\ntype KeyMetaMap = Map;\n\nexport class CompiledKeys {\n payer: PublicKey;\n keyMetaMap: KeyMetaMap;\n\n constructor(payer: PublicKey, keyMetaMap: KeyMetaMap) {\n this.payer = payer;\n this.keyMetaMap = keyMetaMap;\n }\n\n static compile(\n instructions: Array,\n payer: PublicKey,\n ): CompiledKeys {\n const keyMetaMap: KeyMetaMap = new Map();\n const getOrInsertDefault = (pubkey: PublicKey): CompiledKeyMeta => {\n const address = pubkey.toBase58();\n let keyMeta = keyMetaMap.get(address);\n if (keyMeta === undefined) {\n keyMeta = {\n isSigner: false,\n isWritable: false,\n isInvoked: false,\n };\n keyMetaMap.set(address, keyMeta);\n }\n return keyMeta;\n };\n\n const payerKeyMeta = getOrInsertDefault(payer);\n payerKeyMeta.isSigner = true;\n payerKeyMeta.isWritable = true;\n\n for (const ix of instructions) {\n getOrInsertDefault(ix.programId).isInvoked = true;\n for (const accountMeta of ix.keys) {\n const keyMeta = getOrInsertDefault(accountMeta.pubkey);\n keyMeta.isSigner ||= accountMeta.isSigner;\n keyMeta.isWritable ||= accountMeta.isWritable;\n }\n }\n\n return new CompiledKeys(payer, keyMetaMap);\n }\n\n getMessageComponents(): [MessageHeader, Array] {\n const mapEntries = [...this.keyMetaMap.entries()];\n assert(mapEntries.length <= 256, 'Max static account keys length exceeded');\n\n const writableSigners = mapEntries.filter(\n ([, meta]) => meta.isSigner && meta.isWritable,\n );\n const readonlySigners = mapEntries.filter(\n ([, meta]) => meta.isSigner && !meta.isWritable,\n );\n const writableNonSigners = mapEntries.filter(\n ([, meta]) => !meta.isSigner && meta.isWritable,\n );\n const readonlyNonSigners = mapEntries.filter(\n ([, meta]) => !meta.isSigner && !meta.isWritable,\n );\n\n const header: MessageHeader = {\n numRequiredSignatures: writableSigners.length + readonlySigners.length,\n numReadonlySignedAccounts: readonlySigners.length,\n numReadonlyUnsignedAccounts: readonlyNonSigners.length,\n };\n\n // sanity checks\n {\n assert(\n writableSigners.length > 0,\n 'Expected at least one writable signer key',\n );\n const [payerAddress] = writableSigners[0];\n assert(\n payerAddress === this.payer.toBase58(),\n 'Expected first writable signer key to be the fee payer',\n );\n }\n\n const staticAccountKeys = [\n ...writableSigners.map(([address]) => new PublicKey(address)),\n ...readonlySigners.map(([address]) => new PublicKey(address)),\n ...writableNonSigners.map(([address]) => new PublicKey(address)),\n ...readonlyNonSigners.map(([address]) => new PublicKey(address)),\n ];\n\n return [header, staticAccountKeys];\n }\n\n extractTableLookup(\n lookupTable: AddressLookupTableAccount,\n ): [MessageAddressTableLookup, AccountKeysFromLookups] | undefined {\n const [writableIndexes, drainedWritableKeys] =\n this.drainKeysFoundInLookupTable(\n lookupTable.state.addresses,\n keyMeta =>\n !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable,\n );\n const [readonlyIndexes, drainedReadonlyKeys] =\n this.drainKeysFoundInLookupTable(\n lookupTable.state.addresses,\n keyMeta =>\n !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable,\n );\n\n // Don't extract lookup if no keys were found\n if (writableIndexes.length === 0 && readonlyIndexes.length === 0) {\n return;\n }\n\n return [\n {\n accountKey: lookupTable.key,\n writableIndexes,\n readonlyIndexes,\n },\n {\n writable: drainedWritableKeys,\n readonly: drainedReadonlyKeys,\n },\n ];\n }\n\n /** @internal */\n private drainKeysFoundInLookupTable(\n lookupTableEntries: Array,\n keyMetaFilter: (keyMeta: CompiledKeyMeta) => boolean,\n ): [Array, Array] {\n const lookupTableIndexes = new Array();\n const drainedKeys = new Array();\n\n for (const [address, keyMeta] of this.keyMetaMap.entries()) {\n if (keyMetaFilter(keyMeta)) {\n const key = new PublicKey(address);\n const lookupTableIndex = lookupTableEntries.findIndex(entry =>\n entry.equals(key),\n );\n if (lookupTableIndex >= 0) {\n assert(lookupTableIndex < 256, 'Max lookup table index exceeded');\n lookupTableIndexes.push(lookupTableIndex);\n drainedKeys.push(key);\n this.keyMetaMap.delete(address);\n }\n }\n }\n\n return [lookupTableIndexes, drainedKeys];\n }\n}\n","const END_OF_BUFFER_ERROR_MESSAGE = 'Reached end of buffer unexpectedly';\n\n/**\n * Delegates to `Array#shift`, but throws if the array is zero-length.\n */\nexport function guardedShift(byteArray: T[]): T {\n if (byteArray.length === 0) {\n throw new Error(END_OF_BUFFER_ERROR_MESSAGE);\n }\n return byteArray.shift() as T;\n}\n\n/**\n * Delegates to `Array#splice`, but throws if the section being spliced out extends past the end of\n * the array.\n */\nexport function guardedSplice(\n byteArray: T[],\n ...args:\n | [start: number, deleteCount?: number]\n | [start: number, deleteCount: number, ...items: T[]]\n): T[] {\n const [start] = args;\n if (\n args.length === 2 // Implies that `deleteCount` was supplied\n ? start + (args[1] ?? 0) > byteArray.length\n : start >= byteArray.length\n ) {\n throw new Error(END_OF_BUFFER_ERROR_MESSAGE);\n }\n return byteArray.splice(\n ...(args as Parameters),\n );\n}\n","import bs58 from 'bs58';\nimport {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {PublicKey, PUBLIC_KEY_LENGTH} from '../publickey';\nimport type {Blockhash} from '../blockhash';\nimport * as Layout from '../layout';\nimport {PACKET_DATA_SIZE, VERSION_PREFIX_MASK} from '../transaction/constants';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport {toBuffer} from '../utils/to-buffer';\nimport {\n MessageHeader,\n MessageAddressTableLookup,\n MessageCompiledInstruction,\n} from './index';\nimport {TransactionInstruction} from '../transaction';\nimport {CompiledKeys} from './compiled-keys';\nimport {MessageAccountKeys} from './account-keys';\nimport {guardedShift, guardedSplice} from '../utils/guarded-array-utils';\n\n/**\n * An instruction to execute by a program\n *\n * @property {number} programIdIndex\n * @property {number[]} accounts\n * @property {string} data\n */\nexport type CompiledInstruction = {\n /** Index into the transaction keys array indicating the program account that executes this instruction */\n programIdIndex: number;\n /** Ordered indices into the transaction keys array indicating which accounts to pass to the program */\n accounts: number[];\n /** The program input data encoded as base 58 */\n data: string;\n};\n\n/**\n * Message constructor arguments\n */\nexport type MessageArgs = {\n /** The message header, identifying signed and read-only `accountKeys` */\n header: MessageHeader;\n /** All the account keys used by this transaction */\n accountKeys: string[] | PublicKey[];\n /** The hash of a recent ledger block */\n recentBlockhash: Blockhash;\n /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n instructions: CompiledInstruction[];\n};\n\nexport type CompileLegacyArgs = {\n payerKey: PublicKey;\n instructions: Array;\n recentBlockhash: Blockhash;\n};\n\n/**\n * List of instructions to be processed atomically\n */\nexport class Message {\n header: MessageHeader;\n accountKeys: PublicKey[];\n recentBlockhash: Blockhash;\n instructions: CompiledInstruction[];\n\n private indexToProgramIds: Map = new Map<\n number,\n PublicKey\n >();\n\n constructor(args: MessageArgs) {\n this.header = args.header;\n this.accountKeys = args.accountKeys.map(account => new PublicKey(account));\n this.recentBlockhash = args.recentBlockhash;\n this.instructions = args.instructions;\n this.instructions.forEach(ix =>\n this.indexToProgramIds.set(\n ix.programIdIndex,\n this.accountKeys[ix.programIdIndex],\n ),\n );\n }\n\n get version(): 'legacy' {\n return 'legacy';\n }\n\n get staticAccountKeys(): Array {\n return this.accountKeys;\n }\n\n get compiledInstructions(): Array {\n return this.instructions.map(\n (ix): MessageCompiledInstruction => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data),\n }),\n );\n }\n\n get addressTableLookups(): Array {\n return [];\n }\n\n getAccountKeys(): MessageAccountKeys {\n return new MessageAccountKeys(this.staticAccountKeys);\n }\n\n static compile(args: CompileLegacyArgs): Message {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(staticAccountKeys);\n const instructions = accountKeys.compileInstructions(args.instructions).map(\n (ix: MessageCompiledInstruction): CompiledInstruction => ({\n programIdIndex: ix.programIdIndex,\n accounts: ix.accountKeyIndexes,\n data: bs58.encode(ix.data),\n }),\n );\n return new Message({\n header,\n accountKeys: staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n instructions,\n });\n }\n\n isAccountSigner(index: number): boolean {\n return index < this.header.numRequiredSignatures;\n }\n\n isAccountWritable(index: number): boolean {\n const numSignedAccounts = this.header.numRequiredSignatures;\n if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = this.accountKeys.length - numSignedAccounts;\n const numWritableUnsignedAccounts =\n numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts =\n numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n\n isProgramId(index: number): boolean {\n return this.indexToProgramIds.has(index);\n }\n\n programIds(): PublicKey[] {\n return [...this.indexToProgramIds.values()];\n }\n\n nonProgramIds(): PublicKey[] {\n return this.accountKeys.filter((_, index) => !this.isProgramId(index));\n }\n\n serialize(): Buffer {\n const numKeys = this.accountKeys.length;\n\n let keyCount: number[] = [];\n shortvec.encodeLength(keyCount, numKeys);\n\n const instructions = this.instructions.map(instruction => {\n const {accounts, programIdIndex} = instruction;\n const data = Array.from(bs58.decode(instruction.data));\n\n let keyIndicesCount: number[] = [];\n shortvec.encodeLength(keyIndicesCount, accounts.length);\n\n let dataCount: number[] = [];\n shortvec.encodeLength(dataCount, data.length);\n\n return {\n programIdIndex,\n keyIndicesCount: Buffer.from(keyIndicesCount),\n keyIndices: accounts,\n dataLength: Buffer.from(dataCount),\n data,\n };\n });\n\n let instructionCount: number[] = [];\n shortvec.encodeLength(instructionCount, instructions.length);\n let instructionBuffer = Buffer.alloc(PACKET_DATA_SIZE);\n Buffer.from(instructionCount).copy(instructionBuffer);\n let instructionBufferLength = instructionCount.length;\n\n instructions.forEach(instruction => {\n const instructionLayout = BufferLayout.struct<\n Readonly<{\n data: number[];\n dataLength: Uint8Array;\n keyIndices: number[];\n keyIndicesCount: Uint8Array;\n programIdIndex: number;\n }>\n >([\n BufferLayout.u8('programIdIndex'),\n\n BufferLayout.blob(\n instruction.keyIndicesCount.length,\n 'keyIndicesCount',\n ),\n BufferLayout.seq(\n BufferLayout.u8('keyIndex'),\n instruction.keyIndices.length,\n 'keyIndices',\n ),\n BufferLayout.blob(instruction.dataLength.length, 'dataLength'),\n BufferLayout.seq(\n BufferLayout.u8('userdatum'),\n instruction.data.length,\n 'data',\n ),\n ]);\n const length = instructionLayout.encode(\n instruction,\n instructionBuffer,\n instructionBufferLength,\n );\n instructionBufferLength += length;\n });\n instructionBuffer = instructionBuffer.slice(0, instructionBufferLength);\n\n const signDataLayout = BufferLayout.struct<\n Readonly<{\n keyCount: Uint8Array;\n keys: Uint8Array[];\n numReadonlySignedAccounts: Uint8Array;\n numReadonlyUnsignedAccounts: Uint8Array;\n numRequiredSignatures: Uint8Array;\n recentBlockhash: Uint8Array;\n }>\n >([\n BufferLayout.blob(1, 'numRequiredSignatures'),\n BufferLayout.blob(1, 'numReadonlySignedAccounts'),\n BufferLayout.blob(1, 'numReadonlyUnsignedAccounts'),\n BufferLayout.blob(keyCount.length, 'keyCount'),\n BufferLayout.seq(Layout.publicKey('key'), numKeys, 'keys'),\n Layout.publicKey('recentBlockhash'),\n ]);\n\n const transaction = {\n numRequiredSignatures: Buffer.from([this.header.numRequiredSignatures]),\n numReadonlySignedAccounts: Buffer.from([\n this.header.numReadonlySignedAccounts,\n ]),\n numReadonlyUnsignedAccounts: Buffer.from([\n this.header.numReadonlyUnsignedAccounts,\n ]),\n keyCount: Buffer.from(keyCount),\n keys: this.accountKeys.map(key => toBuffer(key.toBytes())),\n recentBlockhash: bs58.decode(this.recentBlockhash),\n };\n\n let signData = Buffer.alloc(2048);\n const length = signDataLayout.encode(transaction, signData);\n instructionBuffer.copy(signData, length);\n return signData.slice(0, length + instructionBuffer.length);\n }\n\n /**\n * Decode a compiled message into a Message object.\n */\n static from(buffer: Buffer | Uint8Array | Array): Message {\n // Slice up wire data\n let byteArray = [...buffer];\n\n const numRequiredSignatures = guardedShift(byteArray);\n if (\n numRequiredSignatures !==\n (numRequiredSignatures & VERSION_PREFIX_MASK)\n ) {\n throw new Error(\n 'Versioned messages must be deserialized with VersionedMessage.deserialize()',\n );\n }\n\n const numReadonlySignedAccounts = guardedShift(byteArray);\n const numReadonlyUnsignedAccounts = guardedShift(byteArray);\n\n const accountCount = shortvec.decodeLength(byteArray);\n let accountKeys = [];\n for (let i = 0; i < accountCount; i++) {\n const account = guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH);\n accountKeys.push(new PublicKey(Buffer.from(account)));\n }\n\n const recentBlockhash = guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH);\n\n const instructionCount = shortvec.decodeLength(byteArray);\n let instructions: CompiledInstruction[] = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = guardedShift(byteArray);\n const accountCount = shortvec.decodeLength(byteArray);\n const accounts = guardedSplice(byteArray, 0, accountCount);\n const dataLength = shortvec.decodeLength(byteArray);\n const dataSlice = guardedSplice(byteArray, 0, dataLength);\n const data = bs58.encode(Buffer.from(dataSlice));\n instructions.push({\n programIdIndex,\n accounts,\n data,\n });\n }\n\n const messageArgs = {\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts,\n },\n recentBlockhash: bs58.encode(Buffer.from(recentBlockhash)),\n accountKeys,\n instructions,\n };\n\n return new Message(messageArgs);\n }\n}\n","import bs58 from 'bs58';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from '../layout';\nimport {Blockhash} from '../blockhash';\nimport {\n MessageHeader,\n MessageAddressTableLookup,\n MessageCompiledInstruction,\n} from './index';\nimport {PublicKey, PUBLIC_KEY_LENGTH} from '../publickey';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport assert from '../utils/assert';\nimport {PACKET_DATA_SIZE, VERSION_PREFIX_MASK} from '../transaction/constants';\nimport {TransactionInstruction} from '../transaction';\nimport {AddressLookupTableAccount} from '../programs';\nimport {CompiledKeys} from './compiled-keys';\nimport {AccountKeysFromLookups, MessageAccountKeys} from './account-keys';\nimport {guardedShift, guardedSplice} from '../utils/guarded-array-utils';\n\n/**\n * Message constructor arguments\n */\nexport type MessageV0Args = {\n /** The message header, identifying signed and read-only `accountKeys` */\n header: MessageHeader;\n /** The static account keys used by this transaction */\n staticAccountKeys: PublicKey[];\n /** The hash of a recent ledger block */\n recentBlockhash: Blockhash;\n /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n compiledInstructions: MessageCompiledInstruction[];\n /** Instructions that will be executed in sequence and committed in one atomic transaction if all succeed. */\n addressTableLookups: MessageAddressTableLookup[];\n};\n\nexport type CompileV0Args = {\n payerKey: PublicKey;\n instructions: Array;\n recentBlockhash: Blockhash;\n addressLookupTableAccounts?: Array;\n};\n\nexport type GetAccountKeysArgs =\n | {\n accountKeysFromLookups?: AccountKeysFromLookups | null;\n }\n | {\n addressLookupTableAccounts?: AddressLookupTableAccount[] | null;\n };\n\nexport class MessageV0 {\n header: MessageHeader;\n staticAccountKeys: Array;\n recentBlockhash: Blockhash;\n compiledInstructions: Array;\n addressTableLookups: Array;\n\n constructor(args: MessageV0Args) {\n this.header = args.header;\n this.staticAccountKeys = args.staticAccountKeys;\n this.recentBlockhash = args.recentBlockhash;\n this.compiledInstructions = args.compiledInstructions;\n this.addressTableLookups = args.addressTableLookups;\n }\n\n get version(): 0 {\n return 0;\n }\n\n get numAccountKeysFromLookups(): number {\n let count = 0;\n for (const lookup of this.addressTableLookups) {\n count += lookup.readonlyIndexes.length + lookup.writableIndexes.length;\n }\n return count;\n }\n\n getAccountKeys(args?: GetAccountKeysArgs): MessageAccountKeys {\n let accountKeysFromLookups: AccountKeysFromLookups | undefined;\n if (\n args &&\n 'accountKeysFromLookups' in args &&\n args.accountKeysFromLookups\n ) {\n if (\n this.numAccountKeysFromLookups !=\n args.accountKeysFromLookups.writable.length +\n args.accountKeysFromLookups.readonly.length\n ) {\n throw new Error(\n 'Failed to get account keys because of a mismatch in the number of account keys from lookups',\n );\n }\n accountKeysFromLookups = args.accountKeysFromLookups;\n } else if (\n args &&\n 'addressLookupTableAccounts' in args &&\n args.addressLookupTableAccounts\n ) {\n accountKeysFromLookups = this.resolveAddressTableLookups(\n args.addressLookupTableAccounts,\n );\n } else if (this.addressTableLookups.length > 0) {\n throw new Error(\n 'Failed to get account keys because address table lookups were not resolved',\n );\n }\n return new MessageAccountKeys(\n this.staticAccountKeys,\n accountKeysFromLookups,\n );\n }\n\n isAccountSigner(index: number): boolean {\n return index < this.header.numRequiredSignatures;\n }\n\n isAccountWritable(index: number): boolean {\n const numSignedAccounts = this.header.numRequiredSignatures;\n const numStaticAccountKeys = this.staticAccountKeys.length;\n if (index >= numStaticAccountKeys) {\n const lookupAccountKeysIndex = index - numStaticAccountKeys;\n const numWritableLookupAccountKeys = this.addressTableLookups.reduce(\n (count, lookup) => count + lookup.writableIndexes.length,\n 0,\n );\n return lookupAccountKeysIndex < numWritableLookupAccountKeys;\n } else if (index >= this.header.numRequiredSignatures) {\n const unsignedAccountIndex = index - numSignedAccounts;\n const numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts;\n const numWritableUnsignedAccounts =\n numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts;\n return unsignedAccountIndex < numWritableUnsignedAccounts;\n } else {\n const numWritableSignedAccounts =\n numSignedAccounts - this.header.numReadonlySignedAccounts;\n return index < numWritableSignedAccounts;\n }\n }\n\n resolveAddressTableLookups(\n addressLookupTableAccounts: AddressLookupTableAccount[],\n ): AccountKeysFromLookups {\n const accountKeysFromLookups: AccountKeysFromLookups = {\n writable: [],\n readonly: [],\n };\n\n for (const tableLookup of this.addressTableLookups) {\n const tableAccount = addressLookupTableAccounts.find(account =>\n account.key.equals(tableLookup.accountKey),\n );\n if (!tableAccount) {\n throw new Error(\n `Failed to find address lookup table account for table key ${tableLookup.accountKey.toBase58()}`,\n );\n }\n\n for (const index of tableLookup.writableIndexes) {\n if (index < tableAccount.state.addresses.length) {\n accountKeysFromLookups.writable.push(\n tableAccount.state.addresses[index],\n );\n } else {\n throw new Error(\n `Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`,\n );\n }\n }\n\n for (const index of tableLookup.readonlyIndexes) {\n if (index < tableAccount.state.addresses.length) {\n accountKeysFromLookups.readonly.push(\n tableAccount.state.addresses[index],\n );\n } else {\n throw new Error(\n `Failed to find address for index ${index} in address lookup table ${tableLookup.accountKey.toBase58()}`,\n );\n }\n }\n }\n\n return accountKeysFromLookups;\n }\n\n static compile(args: CompileV0Args): MessageV0 {\n const compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey);\n\n const addressTableLookups = new Array();\n const accountKeysFromLookups: AccountKeysFromLookups = {\n writable: new Array(),\n readonly: new Array(),\n };\n const lookupTableAccounts = args.addressLookupTableAccounts || [];\n for (const lookupTable of lookupTableAccounts) {\n const extractResult = compiledKeys.extractTableLookup(lookupTable);\n if (extractResult !== undefined) {\n const [addressTableLookup, {writable, readonly}] = extractResult;\n addressTableLookups.push(addressTableLookup);\n accountKeysFromLookups.writable.push(...writable);\n accountKeysFromLookups.readonly.push(...readonly);\n }\n }\n\n const [header, staticAccountKeys] = compiledKeys.getMessageComponents();\n const accountKeys = new MessageAccountKeys(\n staticAccountKeys,\n accountKeysFromLookups,\n );\n const compiledInstructions = accountKeys.compileInstructions(\n args.instructions,\n );\n return new MessageV0({\n header,\n staticAccountKeys,\n recentBlockhash: args.recentBlockhash,\n compiledInstructions,\n addressTableLookups,\n });\n }\n\n serialize(): Uint8Array {\n const encodedStaticAccountKeysLength = Array();\n shortvec.encodeLength(\n encodedStaticAccountKeysLength,\n this.staticAccountKeys.length,\n );\n\n const serializedInstructions = this.serializeInstructions();\n const encodedInstructionsLength = Array();\n shortvec.encodeLength(\n encodedInstructionsLength,\n this.compiledInstructions.length,\n );\n\n const serializedAddressTableLookups = this.serializeAddressTableLookups();\n const encodedAddressTableLookupsLength = Array();\n shortvec.encodeLength(\n encodedAddressTableLookupsLength,\n this.addressTableLookups.length,\n );\n\n const messageLayout = BufferLayout.struct<{\n prefix: number;\n header: MessageHeader;\n staticAccountKeysLength: Uint8Array;\n staticAccountKeys: Array;\n recentBlockhash: Uint8Array;\n instructionsLength: Uint8Array;\n serializedInstructions: Uint8Array;\n addressTableLookupsLength: Uint8Array;\n serializedAddressTableLookups: Uint8Array;\n }>([\n BufferLayout.u8('prefix'),\n BufferLayout.struct(\n [\n BufferLayout.u8('numRequiredSignatures'),\n BufferLayout.u8('numReadonlySignedAccounts'),\n BufferLayout.u8('numReadonlyUnsignedAccounts'),\n ],\n 'header',\n ),\n BufferLayout.blob(\n encodedStaticAccountKeysLength.length,\n 'staticAccountKeysLength',\n ),\n BufferLayout.seq(\n Layout.publicKey(),\n this.staticAccountKeys.length,\n 'staticAccountKeys',\n ),\n Layout.publicKey('recentBlockhash'),\n BufferLayout.blob(encodedInstructionsLength.length, 'instructionsLength'),\n BufferLayout.blob(\n serializedInstructions.length,\n 'serializedInstructions',\n ),\n BufferLayout.blob(\n encodedAddressTableLookupsLength.length,\n 'addressTableLookupsLength',\n ),\n BufferLayout.blob(\n serializedAddressTableLookups.length,\n 'serializedAddressTableLookups',\n ),\n ]);\n\n const serializedMessage = new Uint8Array(PACKET_DATA_SIZE);\n const MESSAGE_VERSION_0_PREFIX = 1 << 7;\n const serializedMessageLength = messageLayout.encode(\n {\n prefix: MESSAGE_VERSION_0_PREFIX,\n header: this.header,\n staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength),\n staticAccountKeys: this.staticAccountKeys.map(key => key.toBytes()),\n recentBlockhash: bs58.decode(this.recentBlockhash),\n instructionsLength: new Uint8Array(encodedInstructionsLength),\n serializedInstructions,\n addressTableLookupsLength: new Uint8Array(\n encodedAddressTableLookupsLength,\n ),\n serializedAddressTableLookups,\n },\n serializedMessage,\n );\n return serializedMessage.slice(0, serializedMessageLength);\n }\n\n private serializeInstructions(): Uint8Array {\n let serializedLength = 0;\n const serializedInstructions = new Uint8Array(PACKET_DATA_SIZE);\n for (const instruction of this.compiledInstructions) {\n const encodedAccountKeyIndexesLength = Array();\n shortvec.encodeLength(\n encodedAccountKeyIndexesLength,\n instruction.accountKeyIndexes.length,\n );\n\n const encodedDataLength = Array();\n shortvec.encodeLength(encodedDataLength, instruction.data.length);\n\n const instructionLayout = BufferLayout.struct<{\n programIdIndex: number;\n encodedAccountKeyIndexesLength: Uint8Array;\n accountKeyIndexes: number[];\n encodedDataLength: Uint8Array;\n data: Uint8Array;\n }>([\n BufferLayout.u8('programIdIndex'),\n BufferLayout.blob(\n encodedAccountKeyIndexesLength.length,\n 'encodedAccountKeyIndexesLength',\n ),\n BufferLayout.seq(\n BufferLayout.u8(),\n instruction.accountKeyIndexes.length,\n 'accountKeyIndexes',\n ),\n BufferLayout.blob(encodedDataLength.length, 'encodedDataLength'),\n BufferLayout.blob(instruction.data.length, 'data'),\n ]);\n\n serializedLength += instructionLayout.encode(\n {\n programIdIndex: instruction.programIdIndex,\n encodedAccountKeyIndexesLength: new Uint8Array(\n encodedAccountKeyIndexesLength,\n ),\n accountKeyIndexes: instruction.accountKeyIndexes,\n encodedDataLength: new Uint8Array(encodedDataLength),\n data: instruction.data,\n },\n serializedInstructions,\n serializedLength,\n );\n }\n\n return serializedInstructions.slice(0, serializedLength);\n }\n\n private serializeAddressTableLookups(): Uint8Array {\n let serializedLength = 0;\n const serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE);\n for (const lookup of this.addressTableLookups) {\n const encodedWritableIndexesLength = Array();\n shortvec.encodeLength(\n encodedWritableIndexesLength,\n lookup.writableIndexes.length,\n );\n\n const encodedReadonlyIndexesLength = Array();\n shortvec.encodeLength(\n encodedReadonlyIndexesLength,\n lookup.readonlyIndexes.length,\n );\n\n const addressTableLookupLayout = BufferLayout.struct<{\n accountKey: Uint8Array;\n encodedWritableIndexesLength: Uint8Array;\n writableIndexes: number[];\n encodedReadonlyIndexesLength: Uint8Array;\n readonlyIndexes: number[];\n }>([\n Layout.publicKey('accountKey'),\n BufferLayout.blob(\n encodedWritableIndexesLength.length,\n 'encodedWritableIndexesLength',\n ),\n BufferLayout.seq(\n BufferLayout.u8(),\n lookup.writableIndexes.length,\n 'writableIndexes',\n ),\n BufferLayout.blob(\n encodedReadonlyIndexesLength.length,\n 'encodedReadonlyIndexesLength',\n ),\n BufferLayout.seq(\n BufferLayout.u8(),\n lookup.readonlyIndexes.length,\n 'readonlyIndexes',\n ),\n ]);\n\n serializedLength += addressTableLookupLayout.encode(\n {\n accountKey: lookup.accountKey.toBytes(),\n encodedWritableIndexesLength: new Uint8Array(\n encodedWritableIndexesLength,\n ),\n writableIndexes: lookup.writableIndexes,\n encodedReadonlyIndexesLength: new Uint8Array(\n encodedReadonlyIndexesLength,\n ),\n readonlyIndexes: lookup.readonlyIndexes,\n },\n serializedAddressTableLookups,\n serializedLength,\n );\n }\n\n return serializedAddressTableLookups.slice(0, serializedLength);\n }\n\n static deserialize(serializedMessage: Uint8Array): MessageV0 {\n let byteArray = [...serializedMessage];\n\n const prefix = guardedShift(byteArray);\n const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n assert(\n prefix !== maskedPrefix,\n `Expected versioned message but received legacy message`,\n );\n\n const version = maskedPrefix;\n assert(\n version === 0,\n `Expected versioned message with version 0 but found version ${version}`,\n );\n\n const header: MessageHeader = {\n numRequiredSignatures: guardedShift(byteArray),\n numReadonlySignedAccounts: guardedShift(byteArray),\n numReadonlyUnsignedAccounts: guardedShift(byteArray),\n };\n\n const staticAccountKeys = [];\n const staticAccountKeysLength = shortvec.decodeLength(byteArray);\n for (let i = 0; i < staticAccountKeysLength; i++) {\n staticAccountKeys.push(\n new PublicKey(guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH)),\n );\n }\n\n const recentBlockhash = bs58.encode(\n guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH),\n );\n\n const instructionCount = shortvec.decodeLength(byteArray);\n const compiledInstructions: MessageCompiledInstruction[] = [];\n for (let i = 0; i < instructionCount; i++) {\n const programIdIndex = guardedShift(byteArray);\n const accountKeyIndexesLength = shortvec.decodeLength(byteArray);\n const accountKeyIndexes = guardedSplice(\n byteArray,\n 0,\n accountKeyIndexesLength,\n );\n const dataLength = shortvec.decodeLength(byteArray);\n const data = new Uint8Array(guardedSplice(byteArray, 0, dataLength));\n compiledInstructions.push({\n programIdIndex,\n accountKeyIndexes,\n data,\n });\n }\n\n const addressTableLookupsCount = shortvec.decodeLength(byteArray);\n const addressTableLookups: MessageAddressTableLookup[] = [];\n for (let i = 0; i < addressTableLookupsCount; i++) {\n const accountKey = new PublicKey(\n guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH),\n );\n const writableIndexesLength = shortvec.decodeLength(byteArray);\n const writableIndexes = guardedSplice(\n byteArray,\n 0,\n writableIndexesLength,\n );\n const readonlyIndexesLength = shortvec.decodeLength(byteArray);\n const readonlyIndexes = guardedSplice(\n byteArray,\n 0,\n readonlyIndexesLength,\n );\n addressTableLookups.push({\n accountKey,\n writableIndexes,\n readonlyIndexes,\n });\n }\n\n return new MessageV0({\n header,\n staticAccountKeys,\n recentBlockhash,\n compiledInstructions,\n addressTableLookups,\n });\n }\n}\n","import {VERSION_PREFIX_MASK} from '../transaction/constants';\nimport {Message} from './legacy';\nimport {MessageV0} from './v0';\n\nexport type VersionedMessage = Message | MessageV0;\n// eslint-disable-next-line no-redeclare\nexport const VersionedMessage = {\n deserializeMessageVersion(serializedMessage: Uint8Array): 'legacy' | number {\n const prefix = serializedMessage[0];\n const maskedPrefix = prefix & VERSION_PREFIX_MASK;\n\n // if the highest bit of the prefix is not set, the message is not versioned\n if (maskedPrefix === prefix) {\n return 'legacy';\n }\n\n // the lower 7 bits of the prefix indicate the message version\n return maskedPrefix;\n },\n\n deserialize: (serializedMessage: Uint8Array): VersionedMessage => {\n const version =\n VersionedMessage.deserializeMessageVersion(serializedMessage);\n if (version === 'legacy') {\n return Message.from(serializedMessage);\n }\n\n if (version === 0) {\n return MessageV0.deserialize(serializedMessage);\n } else {\n throw new Error(\n `Transaction message version ${version} deserialization is not supported`,\n );\n }\n },\n};\n","import bs58 from 'bs58';\nimport {Buffer} from 'buffer';\n\nimport {PACKET_DATA_SIZE, SIGNATURE_LENGTH_IN_BYTES} from './constants';\nimport {Connection} from '../connection';\nimport {Message} from '../message';\nimport {PublicKey} from '../publickey';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport {toBuffer} from '../utils/to-buffer';\nimport invariant from '../utils/assert';\nimport type {Signer} from '../keypair';\nimport type {Blockhash} from '../blockhash';\nimport type {CompiledInstruction} from '../message';\nimport {sign, verify} from '../utils/ed25519';\nimport {guardedSplice} from '../utils/guarded-array-utils';\n\n/** @internal */\ntype MessageSignednessErrors = {\n invalid?: PublicKey[];\n missing?: PublicKey[];\n};\n\n/**\n * Transaction signature as base-58 encoded string\n */\nexport type TransactionSignature = string;\n\nexport const enum TransactionStatus {\n BLOCKHEIGHT_EXCEEDED,\n PROCESSED,\n TIMED_OUT,\n NONCE_INVALID,\n}\n\n/**\n * Default (empty) signature\n */\nconst DEFAULT_SIGNATURE = Buffer.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0);\n\n/**\n * Account metadata used to define instructions\n */\nexport type AccountMeta = {\n /** An account's public key */\n pubkey: PublicKey;\n /** True if an instruction requires a transaction signature matching `pubkey` */\n isSigner: boolean;\n /** True if the `pubkey` can be loaded as a read-write account. */\n isWritable: boolean;\n};\n\n/**\n * List of TransactionInstruction object fields that may be initialized at construction\n */\nexport type TransactionInstructionCtorFields = {\n keys: Array;\n programId: PublicKey;\n data?: Buffer;\n};\n\n/**\n * Configuration object for Transaction.serialize()\n */\nexport type SerializeConfig = {\n /** Require all transaction signatures be present (default: true) */\n requireAllSignatures?: boolean;\n /** Verify provided signatures (default: true) */\n verifySignatures?: boolean;\n};\n\n/**\n * @internal\n */\nexport interface TransactionInstructionJSON {\n keys: {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n }[];\n programId: string;\n data: number[];\n}\n\n/**\n * Transaction Instruction class\n */\nexport class TransactionInstruction {\n /**\n * Public keys to include in this transaction\n * Boolean represents whether this pubkey needs to sign the transaction\n */\n keys: Array;\n\n /**\n * Program Id to execute\n */\n programId: PublicKey;\n\n /**\n * Program input\n */\n data: Buffer = Buffer.alloc(0);\n\n constructor(opts: TransactionInstructionCtorFields) {\n this.programId = opts.programId;\n this.keys = opts.keys;\n if (opts.data) {\n this.data = opts.data;\n }\n }\n\n /**\n * @internal\n */\n toJSON(): TransactionInstructionJSON {\n return {\n keys: this.keys.map(({pubkey, isSigner, isWritable}) => ({\n pubkey: pubkey.toJSON(),\n isSigner,\n isWritable,\n })),\n programId: this.programId.toJSON(),\n data: [...this.data],\n };\n }\n}\n\n/**\n * Pair of signature and corresponding public key\n */\nexport type SignaturePubkeyPair = {\n signature: Buffer | null;\n publicKey: PublicKey;\n};\n\n/**\n * List of Transaction object fields that may be initialized at construction\n */\nexport type TransactionCtorFields_DEPRECATED = {\n /** Optional nonce information used for offline nonce'd transactions */\n nonceInfo?: NonceInformation | null;\n /** The transaction fee payer */\n feePayer?: PublicKey | null;\n /** One or more signatures */\n signatures?: Array;\n /** A recent blockhash */\n recentBlockhash?: Blockhash;\n};\n\n// For backward compatibility; an unfortunate consequence of being\n// forced to over-export types by the documentation generator.\n// See https://github.com/solana-labs/solana/pull/25820\nexport type TransactionCtorFields = TransactionCtorFields_DEPRECATED;\n\n/**\n * Blockhash-based transactions have a lifetime that are defined by\n * the blockhash they include. Any transaction whose blockhash is\n * too old will be rejected.\n */\nexport type TransactionBlockhashCtor = {\n /** The transaction fee payer */\n feePayer?: PublicKey | null;\n /** One or more signatures */\n signatures?: Array;\n /** A recent blockhash */\n blockhash: Blockhash;\n /** the last block chain can advance to before tx is declared expired */\n lastValidBlockHeight: number;\n};\n\n/**\n * Use these options to construct a durable nonce transaction.\n */\nexport type TransactionNonceCtor = {\n /** The transaction fee payer */\n feePayer?: PublicKey | null;\n minContextSlot: number;\n nonceInfo: NonceInformation;\n /** One or more signatures */\n signatures?: Array;\n};\n\n/**\n * Nonce information to be used to build an offline Transaction.\n */\nexport type NonceInformation = {\n /** The current blockhash stored in the nonce */\n nonce: Blockhash;\n /** AdvanceNonceAccount Instruction */\n nonceInstruction: TransactionInstruction;\n};\n\n/**\n * @internal\n */\nexport interface TransactionJSON {\n recentBlockhash: string | null;\n feePayer: string | null;\n nonceInfo: {\n nonce: string;\n nonceInstruction: TransactionInstructionJSON;\n } | null;\n instructions: TransactionInstructionJSON[];\n signers: string[];\n}\n\n/**\n * Transaction class\n */\nexport class Transaction {\n /**\n * Signatures for the transaction. Typically created by invoking the\n * `sign()` method\n */\n signatures: Array = [];\n\n /**\n * The first (payer) Transaction signature\n *\n * @returns {Buffer | null} Buffer of payer's signature\n */\n get signature(): Buffer | null {\n if (this.signatures.length > 0) {\n return this.signatures[0].signature;\n }\n return null;\n }\n\n /**\n * The transaction fee payer\n */\n feePayer?: PublicKey;\n\n /**\n * The instructions to atomically execute\n */\n instructions: Array = [];\n\n /**\n * A recent transaction id. Must be populated by the caller\n */\n recentBlockhash?: Blockhash;\n\n /**\n * the last block chain can advance to before tx is declared expired\n * */\n lastValidBlockHeight?: number;\n\n /**\n * Optional Nonce information. If populated, transaction will use a durable\n * Nonce hash instead of a recentBlockhash. Must be populated by the caller\n */\n nonceInfo?: NonceInformation;\n\n /**\n * If this is a nonce transaction this represents the minimum slot from which\n * to evaluate if the nonce has advanced when attempting to confirm the\n * transaction. This protects against a case where the transaction confirmation\n * logic loads the nonce account from an old slot and assumes the mismatch in\n * nonce value implies that the nonce has been advanced.\n */\n minNonceContextSlot?: number;\n\n /**\n * @internal\n */\n _message?: Message;\n\n /**\n * @internal\n */\n _json?: TransactionJSON;\n\n // Construct a transaction with a blockhash and lastValidBlockHeight\n constructor(opts?: TransactionBlockhashCtor);\n\n // Construct a transaction using a durable nonce\n constructor(opts?: TransactionNonceCtor);\n\n /**\n * @deprecated `TransactionCtorFields` has been deprecated and will be removed in a future version.\n * Please supply a `TransactionBlockhashCtor` instead.\n */\n constructor(opts?: TransactionCtorFields_DEPRECATED);\n\n /**\n * Construct an empty Transaction\n */\n constructor(\n opts?:\n | TransactionBlockhashCtor\n | TransactionNonceCtor\n | TransactionCtorFields_DEPRECATED,\n ) {\n if (!opts) {\n return;\n }\n if (opts.feePayer) {\n this.feePayer = opts.feePayer;\n }\n if (opts.signatures) {\n this.signatures = opts.signatures;\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) {\n const {minContextSlot, nonceInfo} = opts as TransactionNonceCtor;\n this.minNonceContextSlot = minContextSlot;\n this.nonceInfo = nonceInfo;\n } else if (\n Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')\n ) {\n const {blockhash, lastValidBlockHeight} =\n opts as TransactionBlockhashCtor;\n this.recentBlockhash = blockhash;\n this.lastValidBlockHeight = lastValidBlockHeight;\n } else {\n const {recentBlockhash, nonceInfo} =\n opts as TransactionCtorFields_DEPRECATED;\n if (nonceInfo) {\n this.nonceInfo = nonceInfo;\n }\n this.recentBlockhash = recentBlockhash;\n }\n }\n\n /**\n * @internal\n */\n toJSON(): TransactionJSON {\n return {\n recentBlockhash: this.recentBlockhash || null,\n feePayer: this.feePayer ? this.feePayer.toJSON() : null,\n nonceInfo: this.nonceInfo\n ? {\n nonce: this.nonceInfo.nonce,\n nonceInstruction: this.nonceInfo.nonceInstruction.toJSON(),\n }\n : null,\n instructions: this.instructions.map(instruction => instruction.toJSON()),\n signers: this.signatures.map(({publicKey}) => {\n return publicKey.toJSON();\n }),\n };\n }\n\n /**\n * Add one or more instructions to this Transaction\n *\n * @param {Array< Transaction | TransactionInstruction | TransactionInstructionCtorFields >} items - Instructions to add to the Transaction\n */\n add(\n ...items: Array<\n Transaction | TransactionInstruction | TransactionInstructionCtorFields\n >\n ): Transaction {\n if (items.length === 0) {\n throw new Error('No instructions');\n }\n\n items.forEach((item: any) => {\n if ('instructions' in item) {\n this.instructions = this.instructions.concat(item.instructions);\n } else if ('data' in item && 'programId' in item && 'keys' in item) {\n this.instructions.push(item);\n } else {\n this.instructions.push(new TransactionInstruction(item));\n }\n });\n return this;\n }\n\n /**\n * Compile transaction data\n */\n compileMessage(): Message {\n if (\n this._message &&\n JSON.stringify(this.toJSON()) === JSON.stringify(this._json)\n ) {\n return this._message;\n }\n\n let recentBlockhash;\n let instructions: TransactionInstruction[];\n if (this.nonceInfo) {\n recentBlockhash = this.nonceInfo.nonce;\n if (this.instructions[0] != this.nonceInfo.nonceInstruction) {\n instructions = [this.nonceInfo.nonceInstruction, ...this.instructions];\n } else {\n instructions = this.instructions;\n }\n } else {\n recentBlockhash = this.recentBlockhash;\n instructions = this.instructions;\n }\n if (!recentBlockhash) {\n throw new Error('Transaction recentBlockhash required');\n }\n\n if (instructions.length < 1) {\n console.warn('No instructions provided');\n }\n\n let feePayer: PublicKey;\n if (this.feePayer) {\n feePayer = this.feePayer;\n } else if (this.signatures.length > 0 && this.signatures[0].publicKey) {\n // Use implicit fee payer\n feePayer = this.signatures[0].publicKey;\n } else {\n throw new Error('Transaction fee payer required');\n }\n\n for (let i = 0; i < instructions.length; i++) {\n if (instructions[i].programId === undefined) {\n throw new Error(\n `Transaction instruction index ${i} has undefined program id`,\n );\n }\n }\n\n const programIds: string[] = [];\n const accountMetas: AccountMeta[] = [];\n instructions.forEach(instruction => {\n instruction.keys.forEach(accountMeta => {\n accountMetas.push({...accountMeta});\n });\n\n const programId = instruction.programId.toString();\n if (!programIds.includes(programId)) {\n programIds.push(programId);\n }\n });\n\n // Append programID account metas\n programIds.forEach(programId => {\n accountMetas.push({\n pubkey: new PublicKey(programId),\n isSigner: false,\n isWritable: false,\n });\n });\n\n // Cull duplicate account metas\n const uniqueMetas: AccountMeta[] = [];\n accountMetas.forEach(accountMeta => {\n const pubkeyString = accountMeta.pubkey.toString();\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.toString() === pubkeyString;\n });\n if (uniqueIndex > -1) {\n uniqueMetas[uniqueIndex].isWritable =\n uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable;\n uniqueMetas[uniqueIndex].isSigner =\n uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner;\n } else {\n uniqueMetas.push(accountMeta);\n }\n });\n\n // Sort. Prioritizing first by signer, then by writable\n uniqueMetas.sort(function (x, y) {\n if (x.isSigner !== y.isSigner) {\n // Signers always come before non-signers\n return x.isSigner ? -1 : 1;\n }\n if (x.isWritable !== y.isWritable) {\n // Writable accounts always come before read-only accounts\n return x.isWritable ? -1 : 1;\n }\n // Otherwise, sort by pubkey, stringwise.\n const options = {\n localeMatcher: 'best fit',\n usage: 'sort',\n sensitivity: 'variant',\n ignorePunctuation: false,\n numeric: false,\n caseFirst: 'lower',\n } as Intl.CollatorOptions;\n return x.pubkey\n .toBase58()\n .localeCompare(y.pubkey.toBase58(), 'en', options);\n });\n\n // Move fee payer to the front\n const feePayerIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(feePayer);\n });\n if (feePayerIndex > -1) {\n const [payerMeta] = uniqueMetas.splice(feePayerIndex, 1);\n payerMeta.isSigner = true;\n payerMeta.isWritable = true;\n uniqueMetas.unshift(payerMeta);\n } else {\n uniqueMetas.unshift({\n pubkey: feePayer,\n isSigner: true,\n isWritable: true,\n });\n }\n\n // Disallow unknown signers\n for (const signature of this.signatures) {\n const uniqueIndex = uniqueMetas.findIndex(x => {\n return x.pubkey.equals(signature.publicKey);\n });\n if (uniqueIndex > -1) {\n if (!uniqueMetas[uniqueIndex].isSigner) {\n uniqueMetas[uniqueIndex].isSigner = true;\n console.warn(\n 'Transaction references a signature that is unnecessary, ' +\n 'only the fee payer and instruction signer accounts should sign a transaction. ' +\n 'This behavior is deprecated and will throw an error in the next major version release.',\n );\n }\n } else {\n throw new Error(`unknown signer: ${signature.publicKey.toString()}`);\n }\n }\n\n let numRequiredSignatures = 0;\n let numReadonlySignedAccounts = 0;\n let numReadonlyUnsignedAccounts = 0;\n\n // Split out signing from non-signing keys and count header values\n const signedKeys: string[] = [];\n const unsignedKeys: string[] = [];\n uniqueMetas.forEach(({pubkey, isSigner, isWritable}) => {\n if (isSigner) {\n signedKeys.push(pubkey.toString());\n numRequiredSignatures += 1;\n if (!isWritable) {\n numReadonlySignedAccounts += 1;\n }\n } else {\n unsignedKeys.push(pubkey.toString());\n if (!isWritable) {\n numReadonlyUnsignedAccounts += 1;\n }\n }\n });\n\n const accountKeys = signedKeys.concat(unsignedKeys);\n const compiledInstructions: CompiledInstruction[] = instructions.map(\n instruction => {\n const {data, programId} = instruction;\n return {\n programIdIndex: accountKeys.indexOf(programId.toString()),\n accounts: instruction.keys.map(meta =>\n accountKeys.indexOf(meta.pubkey.toString()),\n ),\n data: bs58.encode(data),\n };\n },\n );\n\n compiledInstructions.forEach(instruction => {\n invariant(instruction.programIdIndex >= 0);\n instruction.accounts.forEach(keyIndex => invariant(keyIndex >= 0));\n });\n\n return new Message({\n header: {\n numRequiredSignatures,\n numReadonlySignedAccounts,\n numReadonlyUnsignedAccounts,\n },\n accountKeys,\n recentBlockhash,\n instructions: compiledInstructions,\n });\n }\n\n /**\n * @internal\n */\n _compile(): Message {\n const message = this.compileMessage();\n const signedKeys = message.accountKeys.slice(\n 0,\n message.header.numRequiredSignatures,\n );\n\n if (this.signatures.length === signedKeys.length) {\n const valid = this.signatures.every((pair, index) => {\n return signedKeys[index].equals(pair.publicKey);\n });\n\n if (valid) return message;\n }\n\n this.signatures = signedKeys.map(publicKey => ({\n signature: null,\n publicKey,\n }));\n\n return message;\n }\n\n /**\n * Get a buffer of the Transaction data that need to be covered by signatures\n */\n serializeMessage(): Buffer {\n return this._compile().serialize();\n }\n\n /**\n * Get the estimated fee associated with a transaction\n *\n * @param {Connection} connection Connection to RPC Endpoint.\n *\n * @returns {Promise} The estimated fee for the transaction\n */\n async getEstimatedFee(connection: Connection): Promise {\n return (await connection.getFeeForMessage(this.compileMessage())).value;\n }\n\n /**\n * Specify the public keys which will be used to sign the Transaction.\n * The first signer will be used as the transaction fee payer account.\n *\n * Signatures can be added with either `partialSign` or `addSignature`\n *\n * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be\n * specified and it can be set in the Transaction constructor or with the\n * `feePayer` property.\n */\n setSigners(...signers: Array) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n const seen = new Set();\n this.signatures = signers\n .filter(publicKey => {\n const key = publicKey.toString();\n if (seen.has(key)) {\n return false;\n } else {\n seen.add(key);\n return true;\n }\n })\n .map(publicKey => ({signature: null, publicKey}));\n }\n\n /**\n * Sign the Transaction with the specified signers. Multiple signatures may\n * be applied to a Transaction. The first signature is considered \"primary\"\n * and is used identify and confirm transactions.\n *\n * If the Transaction `feePayer` is not set, the first signer will be used\n * as the transaction fee payer account.\n *\n * Transaction fields should not be modified after the first call to `sign`,\n * as doing so may invalidate the signature and cause the Transaction to be\n * rejected.\n *\n * The Transaction must be assigned a valid `recentBlockhash` before invoking this method\n *\n * @param {Array} signers Array of signers that will sign the transaction\n */\n sign(...signers: Array) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n\n this.signatures = uniqueSigners.map(signer => ({\n signature: null,\n publicKey: signer.publicKey,\n }));\n\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * Partially sign a transaction with the specified accounts. All accounts must\n * correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * All the caveats from the `sign` method apply to `partialSign`\n *\n * @param {Array} signers Array of signers that will sign the transaction\n */\n partialSign(...signers: Array) {\n if (signers.length === 0) {\n throw new Error('No signers');\n }\n\n // Dedupe signers\n const seen = new Set();\n const uniqueSigners = [];\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n\n const message = this._compile();\n this._partialSign(message, ...uniqueSigners);\n }\n\n /**\n * @internal\n */\n _partialSign(message: Message, ...signers: Array) {\n const signData = message.serialize();\n signers.forEach(signer => {\n const signature = sign(signData, signer.secretKey);\n this._addSignature(signer.publicKey, toBuffer(signature));\n });\n }\n\n /**\n * Add an externally created signature to a transaction. The public key\n * must correspond to either the fee payer or a signer account in the transaction\n * instructions.\n *\n * @param {PublicKey} pubkey Public key that will be added to the transaction.\n * @param {Buffer} signature An externally created signature to add to the transaction.\n */\n addSignature(pubkey: PublicKey, signature: Buffer) {\n this._compile(); // Ensure signatures array is populated\n this._addSignature(pubkey, signature);\n }\n\n /**\n * @internal\n */\n _addSignature(pubkey: PublicKey, signature: Buffer) {\n invariant(signature.length === 64);\n\n const index = this.signatures.findIndex(sigpair =>\n pubkey.equals(sigpair.publicKey),\n );\n if (index < 0) {\n throw new Error(`unknown signer: ${pubkey.toString()}`);\n }\n\n this.signatures[index].signature = Buffer.from(signature);\n }\n\n /**\n * Verify signatures of a Transaction\n * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one.\n * If no boolean is provided, we expect a fully signed Transaction by default.\n *\n * @param {boolean} [requireAllSignatures=true] Require a fully signed Transaction\n */\n verifySignatures(requireAllSignatures: boolean = true): boolean {\n const signatureErrors = this._getMessageSignednessErrors(\n this.serializeMessage(),\n requireAllSignatures,\n );\n return !signatureErrors;\n }\n\n /**\n * @internal\n */\n _getMessageSignednessErrors(\n message: Uint8Array,\n requireAllSignatures: boolean,\n ): MessageSignednessErrors | undefined {\n const errors: MessageSignednessErrors = {};\n for (const {signature, publicKey} of this.signatures) {\n if (signature === null) {\n if (requireAllSignatures) {\n (errors.missing ||= []).push(publicKey);\n }\n } else {\n if (!verify(signature, message, publicKey.toBytes())) {\n (errors.invalid ||= []).push(publicKey);\n }\n }\n }\n return errors.invalid || errors.missing ? errors : undefined;\n }\n\n /**\n * Serialize the Transaction in the wire format.\n *\n * @param {Buffer} [config] Config of transaction.\n *\n * @returns {Buffer} Signature of transaction in wire format.\n */\n serialize(config?: SerializeConfig): Buffer {\n const {requireAllSignatures, verifySignatures} = Object.assign(\n {requireAllSignatures: true, verifySignatures: true},\n config,\n );\n\n const signData = this.serializeMessage();\n if (verifySignatures) {\n const sigErrors = this._getMessageSignednessErrors(\n signData,\n requireAllSignatures,\n );\n if (sigErrors) {\n let errorMessage = 'Signature verification failed.';\n if (sigErrors.invalid) {\n errorMessage += `\\nInvalid signature for public key${\n sigErrors.invalid.length === 1 ? '' : '(s)'\n } [\\`${sigErrors.invalid.map(p => p.toBase58()).join('`, `')}\\`].`;\n }\n if (sigErrors.missing) {\n errorMessage += `\\nMissing signature for public key${\n sigErrors.missing.length === 1 ? '' : '(s)'\n } [\\`${sigErrors.missing.map(p => p.toBase58()).join('`, `')}\\`].`;\n }\n throw new Error(errorMessage);\n }\n }\n\n return this._serialize(signData);\n }\n\n /**\n * @internal\n */\n _serialize(signData: Buffer): Buffer {\n const {signatures} = this;\n const signatureCount: number[] = [];\n shortvec.encodeLength(signatureCount, signatures.length);\n const transactionLength =\n signatureCount.length + signatures.length * 64 + signData.length;\n const wireTransaction = Buffer.alloc(transactionLength);\n invariant(signatures.length < 256);\n Buffer.from(signatureCount).copy(wireTransaction, 0);\n signatures.forEach(({signature}, index) => {\n if (signature !== null) {\n invariant(signature.length === 64, `signature has invalid length`);\n Buffer.from(signature).copy(\n wireTransaction,\n signatureCount.length + index * 64,\n );\n }\n });\n signData.copy(\n wireTransaction,\n signatureCount.length + signatures.length * 64,\n );\n invariant(\n wireTransaction.length <= PACKET_DATA_SIZE,\n `Transaction too large: ${wireTransaction.length} > ${PACKET_DATA_SIZE}`,\n );\n return wireTransaction;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get keys(): Array {\n invariant(this.instructions.length === 1);\n return this.instructions[0].keys.map(keyObj => keyObj.pubkey);\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get programId(): PublicKey {\n invariant(this.instructions.length === 1);\n return this.instructions[0].programId;\n }\n\n /**\n * Deprecated method\n * @internal\n */\n get data(): Buffer {\n invariant(this.instructions.length === 1);\n return this.instructions[0].data;\n }\n\n /**\n * Parse a wire transaction into a Transaction object.\n *\n * @param {Buffer | Uint8Array | Array} buffer Signature of wire Transaction\n *\n * @returns {Transaction} Transaction associated with the signature\n */\n static from(buffer: Buffer | Uint8Array | Array): Transaction {\n // Slice up wire data\n let byteArray = [...buffer];\n\n const signatureCount = shortvec.decodeLength(byteArray);\n let signatures = [];\n for (let i = 0; i < signatureCount; i++) {\n const signature = guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES);\n signatures.push(bs58.encode(Buffer.from(signature)));\n }\n\n return Transaction.populate(Message.from(byteArray), signatures);\n }\n\n /**\n * Populate Transaction object from message and signatures\n *\n * @param {Message} message Message of transaction\n * @param {Array} signatures List of signatures to assign to the transaction\n *\n * @returns {Transaction} The populated Transaction\n */\n static populate(\n message: Message,\n signatures: Array = [],\n ): Transaction {\n const transaction = new Transaction();\n transaction.recentBlockhash = message.recentBlockhash;\n if (message.header.numRequiredSignatures > 0) {\n transaction.feePayer = message.accountKeys[0];\n }\n signatures.forEach((signature, index) => {\n const sigPubkeyPair = {\n signature:\n signature == bs58.encode(DEFAULT_SIGNATURE)\n ? null\n : bs58.decode(signature),\n publicKey: message.accountKeys[index],\n };\n transaction.signatures.push(sigPubkeyPair);\n });\n\n message.instructions.forEach(instruction => {\n const keys = instruction.accounts.map(account => {\n const pubkey = message.accountKeys[account];\n return {\n pubkey,\n isSigner:\n transaction.signatures.some(\n keyObj => keyObj.publicKey.toString() === pubkey.toString(),\n ) || message.isAccountSigner(account),\n isWritable: message.isAccountWritable(account),\n };\n });\n\n transaction.instructions.push(\n new TransactionInstruction({\n keys,\n programId: message.accountKeys[instruction.programIdIndex],\n data: bs58.decode(instruction.data),\n }),\n );\n });\n\n transaction._message = message;\n transaction._json = transaction.toJSON();\n\n return transaction;\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {Signer} from '../keypair';\nimport assert from '../utils/assert';\nimport {VersionedMessage} from '../message/versioned';\nimport {SIGNATURE_LENGTH_IN_BYTES} from './constants';\nimport * as shortvec from '../utils/shortvec-encoding';\nimport * as Layout from '../layout';\nimport {sign} from '../utils/ed25519';\nimport {PublicKey} from '../publickey';\nimport {guardedSplice} from '../utils/guarded-array-utils';\n\nexport type TransactionVersion = 'legacy' | 0;\n\n/**\n * Versioned transaction class\n */\nexport class VersionedTransaction {\n signatures: Array;\n message: VersionedMessage;\n\n get version(): TransactionVersion {\n return this.message.version;\n }\n\n constructor(message: VersionedMessage, signatures?: Array) {\n if (signatures !== undefined) {\n assert(\n signatures.length === message.header.numRequiredSignatures,\n 'Expected signatures length to be equal to the number of required signatures',\n );\n this.signatures = signatures;\n } else {\n const defaultSignatures = [];\n for (let i = 0; i < message.header.numRequiredSignatures; i++) {\n defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES));\n }\n this.signatures = defaultSignatures;\n }\n this.message = message;\n }\n\n serialize(): Uint8Array {\n const serializedMessage = this.message.serialize();\n\n const encodedSignaturesLength = Array();\n shortvec.encodeLength(encodedSignaturesLength, this.signatures.length);\n\n const transactionLayout = BufferLayout.struct<{\n encodedSignaturesLength: Uint8Array;\n signatures: Array;\n serializedMessage: Uint8Array;\n }>([\n BufferLayout.blob(\n encodedSignaturesLength.length,\n 'encodedSignaturesLength',\n ),\n BufferLayout.seq(\n Layout.signature(),\n this.signatures.length,\n 'signatures',\n ),\n BufferLayout.blob(serializedMessage.length, 'serializedMessage'),\n ]);\n\n const serializedTransaction = new Uint8Array(2048);\n const serializedTransactionLength = transactionLayout.encode(\n {\n encodedSignaturesLength: new Uint8Array(encodedSignaturesLength),\n signatures: this.signatures,\n serializedMessage,\n },\n serializedTransaction,\n );\n\n return serializedTransaction.slice(0, serializedTransactionLength);\n }\n\n static deserialize(serializedTransaction: Uint8Array): VersionedTransaction {\n let byteArray = [...serializedTransaction];\n\n const signatures = [];\n const signaturesLength = shortvec.decodeLength(byteArray);\n for (let i = 0; i < signaturesLength; i++) {\n signatures.push(\n new Uint8Array(guardedSplice(byteArray, 0, SIGNATURE_LENGTH_IN_BYTES)),\n );\n }\n\n const message = VersionedMessage.deserialize(new Uint8Array(byteArray));\n return new VersionedTransaction(message, signatures);\n }\n\n sign(signers: Array) {\n const messageData = this.message.serialize();\n const signerPubkeys = this.message.staticAccountKeys.slice(\n 0,\n this.message.header.numRequiredSignatures,\n );\n for (const signer of signers) {\n const signerIndex = signerPubkeys.findIndex(pubkey =>\n pubkey.equals(signer.publicKey),\n );\n assert(\n signerIndex >= 0,\n `Cannot sign with non signer key ${signer.publicKey.toBase58()}`,\n );\n this.signatures[signerIndex] = sign(messageData, signer.secretKey);\n }\n }\n\n addSignature(publicKey: PublicKey, signature: Uint8Array) {\n assert(signature.byteLength === 64, 'Signature must be 64 bytes long');\n const signerPubkeys = this.message.staticAccountKeys.slice(\n 0,\n this.message.header.numRequiredSignatures,\n );\n const signerIndex = signerPubkeys.findIndex(pubkey =>\n pubkey.equals(publicKey),\n );\n assert(\n signerIndex >= 0,\n `Can not add signature; \\`${publicKey.toBase58()}\\` is not required to sign this transaction`,\n );\n this.signatures[signerIndex] = signature;\n }\n}\n","// TODO: These constants should be removed in favor of reading them out of a\n// Syscall account\n\n/**\n * @internal\n */\nexport const NUM_TICKS_PER_SECOND = 160;\n\n/**\n * @internal\n */\nexport const DEFAULT_TICKS_PER_SLOT = 64;\n\n/**\n * @internal\n */\nexport const NUM_SLOTS_PER_SECOND =\n NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT;\n\n/**\n * @internal\n */\nexport const MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND;\n","import {PublicKey} from './publickey';\n\nexport const SYSVAR_CLOCK_PUBKEY = new PublicKey(\n 'SysvarC1ock11111111111111111111111111111111',\n);\n\nexport const SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey(\n 'SysvarEpochSchedu1e111111111111111111111111',\n);\n\nexport const SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey(\n 'Sysvar1nstructions1111111111111111111111111',\n);\n\nexport const SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey(\n 'SysvarRecentB1ockHashes11111111111111111111',\n);\n\nexport const SYSVAR_RENT_PUBKEY = new PublicKey(\n 'SysvarRent111111111111111111111111111111111',\n);\n\nexport const SYSVAR_REWARDS_PUBKEY = new PublicKey(\n 'SysvarRewards111111111111111111111111111111',\n);\n\nexport const SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey(\n 'SysvarS1otHashes111111111111111111111111111',\n);\n\nexport const SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey(\n 'SysvarS1otHistory11111111111111111111111111',\n);\n\nexport const SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey(\n 'SysvarStakeHistory1111111111111111111111111',\n);\n","import {Connection} from './connection';\nimport {TransactionSignature} from './transaction';\n\nexport class SendTransactionError extends Error {\n private signature: TransactionSignature;\n private transactionMessage: string;\n private transactionLogs: string[] | Promise | undefined;\n\n constructor({\n action,\n signature,\n transactionMessage,\n logs,\n }: {\n action: 'send' | 'simulate';\n signature: TransactionSignature;\n transactionMessage: string;\n logs?: string[];\n }) {\n const maybeLogsOutput = logs\n ? `Logs: \\n${JSON.stringify(logs.slice(-10), null, 2)}. `\n : '';\n const guideText =\n '\\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.';\n let message: string;\n switch (action) {\n case 'send':\n message =\n `Transaction ${signature} resulted in an error. \\n` +\n `${transactionMessage}. ` +\n maybeLogsOutput +\n guideText;\n break;\n case 'simulate':\n message =\n `Simulation failed. \\nMessage: ${transactionMessage}. \\n` +\n maybeLogsOutput +\n guideText;\n break;\n default: {\n message = `Unknown action '${((a: never) => a)(action)}'`;\n }\n }\n super(message);\n\n this.signature = signature;\n this.transactionMessage = transactionMessage;\n this.transactionLogs = logs ? logs : undefined;\n }\n\n get transactionError(): {message: string; logs?: string[]} {\n return {\n message: this.transactionMessage,\n logs: Array.isArray(this.transactionLogs)\n ? this.transactionLogs\n : undefined,\n };\n }\n\n /* @deprecated Use `await getLogs()` instead */\n get logs(): string[] | undefined {\n const cachedLogs = this.transactionLogs;\n if (\n cachedLogs != null &&\n typeof cachedLogs === 'object' &&\n 'then' in cachedLogs\n ) {\n return undefined;\n }\n return cachedLogs;\n }\n\n async getLogs(connection: Connection): Promise {\n if (!Array.isArray(this.transactionLogs)) {\n this.transactionLogs = new Promise((resolve, reject) => {\n connection\n .getTransaction(this.signature)\n .then(tx => {\n if (tx && tx.meta && tx.meta.logMessages) {\n const logs = tx.meta.logMessages;\n this.transactionLogs = logs;\n resolve(logs);\n } else {\n reject(new Error('Log messages not found'));\n }\n })\n .catch(reject);\n });\n }\n return await this.transactionLogs;\n }\n}\n\n// Keep in sync with client/src/rpc_custom_errors.rs\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nexport const SolanaJSONRPCErrorCode = {\n JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001,\n JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003,\n JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004,\n JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005,\n JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006,\n JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007,\n JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008,\n JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009,\n JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010,\n JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011,\n JSON_RPC_SCAN_ERROR: -32012,\n JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013,\n JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014,\n JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015,\n JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016,\n} as const;\nexport type SolanaJSONRPCErrorCodeEnum =\n (typeof SolanaJSONRPCErrorCode)[keyof typeof SolanaJSONRPCErrorCode];\n\nexport class SolanaJSONRPCError extends Error {\n code: SolanaJSONRPCErrorCodeEnum | unknown;\n data?: any;\n constructor(\n {\n code,\n message,\n data,\n }: Readonly<{code: unknown; message: string; data?: any}>,\n customMessage?: string,\n ) {\n super(customMessage != null ? `${customMessage}: ${message}` : message);\n this.code = code;\n this.data = data;\n this.name = 'SolanaJSONRPCError';\n }\n}\n","import {Connection, SignatureResult} from '../connection';\nimport {Transaction} from '../transaction';\nimport type {ConfirmOptions} from '../connection';\nimport type {Signer} from '../keypair';\nimport type {TransactionSignature} from '../transaction';\nimport {SendTransactionError} from '../errors';\n\n/**\n * Sign, send and confirm a transaction.\n *\n * If `commitment` option is not specified, defaults to 'max' commitment.\n *\n * @param {Connection} connection\n * @param {Transaction} transaction\n * @param {Array} signers\n * @param {ConfirmOptions} [options]\n * @returns {Promise}\n */\nexport async function sendAndConfirmTransaction(\n connection: Connection,\n transaction: Transaction,\n signers: Array,\n options?: ConfirmOptions &\n Readonly<{\n // A signal that, when aborted, cancels any outstanding transaction confirmation operations\n abortSignal?: AbortSignal;\n }>,\n): Promise {\n const sendOptions = options && {\n skipPreflight: options.skipPreflight,\n preflightCommitment: options.preflightCommitment || options.commitment,\n maxRetries: options.maxRetries,\n minContextSlot: options.minContextSlot,\n };\n\n const signature = await connection.sendTransaction(\n transaction,\n signers,\n sendOptions,\n );\n\n let status: SignatureResult;\n if (\n transaction.recentBlockhash != null &&\n transaction.lastValidBlockHeight != null\n ) {\n status = (\n await connection.confirmTransaction(\n {\n abortSignal: options?.abortSignal,\n signature: signature,\n blockhash: transaction.recentBlockhash,\n lastValidBlockHeight: transaction.lastValidBlockHeight,\n },\n options && options.commitment,\n )\n ).value;\n } else if (\n transaction.minNonceContextSlot != null &&\n transaction.nonceInfo != null\n ) {\n const {nonceInstruction} = transaction.nonceInfo;\n const nonceAccountPubkey = nonceInstruction.keys[0].pubkey;\n status = (\n await connection.confirmTransaction(\n {\n abortSignal: options?.abortSignal,\n minContextSlot: transaction.minNonceContextSlot,\n nonceAccountPubkey,\n nonceValue: transaction.nonceInfo.nonce,\n signature,\n },\n options && options.commitment,\n )\n ).value;\n } else {\n if (options?.abortSignal != null) {\n console.warn(\n 'sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' +\n 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' +\n 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.',\n );\n }\n status = (\n await connection.confirmTransaction(\n signature,\n options && options.commitment,\n )\n ).value;\n }\n\n if (status.err) {\n if (signature != null) {\n throw new SendTransactionError({\n action: 'send',\n signature: signature,\n transactionMessage: `Status: (${JSON.stringify(status)})`,\n });\n }\n throw new Error(\n `Transaction ${signature} failed (${JSON.stringify(status)})`,\n );\n }\n\n return signature;\n}\n","// zzz\nexport function sleep(ms: number): Promise {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from './layout';\n\nexport interface IInstructionInputData {\n readonly instruction: number;\n}\n\n/**\n * @internal\n */\nexport type InstructionType = {\n /** The Instruction index (from solana upstream program) */\n index: number;\n /** The BufferLayout to use to build data */\n layout: BufferLayout.Layout;\n};\n\n/**\n * Populate a buffer of instruction data using an InstructionType\n * @internal\n */\nexport function encodeData(\n type: InstructionType,\n fields?: any,\n): Buffer {\n const allocLength =\n type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);\n const data = Buffer.alloc(allocLength);\n const layoutFields = Object.assign({instruction: type.index}, fields);\n type.layout.encode(layoutFields, data);\n return data;\n}\n\n/**\n * Decode instruction data buffer using an InstructionType\n * @internal\n */\nexport function decodeData(\n type: InstructionType,\n buffer: Buffer,\n): TInputData {\n let data: TInputData;\n try {\n data = type.layout.decode(buffer);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n\n if (data.instruction !== type.index) {\n throw new Error(\n `invalid instruction; instruction index mismatch ${data.instruction} != ${type.index}`,\n );\n }\n\n return data;\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\n/**\n * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11\n *\n * @internal\n */\nexport const FeeCalculatorLayout = BufferLayout.nu64('lamportsPerSignature');\n\n/**\n * Calculator for transaction fees.\n *\n * @deprecated Deprecated since Solana v1.8.0.\n */\nexport interface FeeCalculator {\n /** Cost in lamports to validate a signature. */\n lamportsPerSignature: number;\n}\n","import * as BufferLayout from '@solana/buffer-layout';\nimport {Buffer} from 'buffer';\n\nimport * as Layout from './layout';\nimport {PublicKey} from './publickey';\nimport type {FeeCalculator} from './fee-calculator';\nimport {FeeCalculatorLayout} from './fee-calculator';\nimport {toBuffer} from './utils/to-buffer';\n\n/**\n * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32\n *\n * @internal\n */\nconst NonceAccountLayout = BufferLayout.struct<\n Readonly<{\n authorizedPubkey: Uint8Array;\n feeCalculator: Readonly<{\n lamportsPerSignature: number;\n }>;\n nonce: Uint8Array;\n state: number;\n version: number;\n }>\n>([\n BufferLayout.u32('version'),\n BufferLayout.u32('state'),\n Layout.publicKey('authorizedPubkey'),\n Layout.publicKey('nonce'),\n BufferLayout.struct>(\n [FeeCalculatorLayout],\n 'feeCalculator',\n ),\n]);\n\nexport const NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span;\n\n/**\n * A durable nonce is a 32 byte value encoded as a base58 string.\n */\nexport type DurableNonce = string;\n\ntype NonceAccountArgs = {\n authorizedPubkey: PublicKey;\n nonce: DurableNonce;\n feeCalculator: FeeCalculator;\n};\n\n/**\n * NonceAccount class\n */\nexport class NonceAccount {\n authorizedPubkey: PublicKey;\n nonce: DurableNonce;\n feeCalculator: FeeCalculator;\n\n /**\n * @internal\n */\n constructor(args: NonceAccountArgs) {\n this.authorizedPubkey = args.authorizedPubkey;\n this.nonce = args.nonce;\n this.feeCalculator = args.feeCalculator;\n }\n\n /**\n * Deserialize NonceAccount from the account data.\n *\n * @param buffer account data\n * @return NonceAccount\n */\n static fromAccountData(\n buffer: Buffer | Uint8Array | Array,\n ): NonceAccount {\n const nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0);\n return new NonceAccount({\n authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey),\n nonce: new PublicKey(nonceAccount.nonce).toString(),\n feeCalculator: nonceAccount.feeCalculator,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport {blob, Layout} from '@solana/buffer-layout';\nimport {toBigIntLE, toBufferLE} from 'bigint-buffer';\n\ninterface EncodeDecode {\n decode(buffer: Buffer, offset?: number): T;\n encode(src: T, buffer: Buffer, offset?: number): number;\n}\n\nconst encodeDecode = (layout: Layout): EncodeDecode => {\n const decode = layout.decode.bind(layout);\n const encode = layout.encode.bind(layout);\n return {decode, encode};\n};\n\nconst bigInt =\n (length: number) =>\n (property?: string): Layout => {\n const layout = blob(length, property);\n const {encode, decode} = encodeDecode(layout);\n\n const bigIntLayout = layout as Layout as Layout;\n\n bigIntLayout.decode = (buffer: Buffer, offset: number) => {\n const src = decode(buffer, offset);\n return toBigIntLE(Buffer.from(src));\n };\n\n bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {\n const src = toBufferLE(bigInt, length);\n return encode(src, buffer, offset);\n };\n\n return bigIntLayout;\n };\n\nexport const u64 = bigInt(8);\n\nexport const u128 = bigInt(16);\n\nexport const u192 = bigInt(24);\n\nexport const u256 = bigInt(32);\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {NONCE_ACCOUNT_LENGTH} from '../nonce-account';\nimport {PublicKey} from '../publickey';\nimport {SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\nimport {u64} from '../utils/bigint';\n\n/**\n * Create account system transaction params\n */\nexport type CreateAccountParams = {\n /** The account that will transfer lamports to the created account */\n fromPubkey: PublicKey;\n /** Public key of the created account */\n newAccountPubkey: PublicKey;\n /** Amount of lamports to transfer to the created account */\n lamports: number;\n /** Amount of space in bytes to allocate to the created account */\n space: number;\n /** Public key of the program to assign as the owner of the created account */\n programId: PublicKey;\n};\n\n/**\n * Transfer system transaction params\n */\nexport type TransferParams = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: number | bigint;\n};\n\n/**\n * Assign system transaction params\n */\nexport type AssignParams = {\n /** Public key of the account which will be assigned a new owner */\n accountPubkey: PublicKey;\n /** Public key of the program to assign as the owner */\n programId: PublicKey;\n};\n\n/**\n * Create account with seed system transaction params\n */\nexport type CreateAccountWithSeedParams = {\n /** The account that will transfer lamports to the created account */\n fromPubkey: PublicKey;\n /** Public key of the created account. Must be pre-calculated with PublicKey.createWithSeed() */\n newAccountPubkey: PublicKey;\n /** Base public key to use to derive the address of the created account. Must be the same as the base key used to create `newAccountPubkey` */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the created account. Must be the same as the seed used to create `newAccountPubkey` */\n seed: string;\n /** Amount of lamports to transfer to the created account */\n lamports: number;\n /** Amount of space in bytes to allocate to the created account */\n space: number;\n /** Public key of the program to assign as the owner of the created account */\n programId: PublicKey;\n};\n\n/**\n * Create nonce account system transaction params\n */\nexport type CreateNonceAccountParams = {\n /** The account that will transfer lamports to the created nonce account */\n fromPubkey: PublicKey;\n /** Public key of the created nonce account */\n noncePubkey: PublicKey;\n /** Public key to set as authority of the created nonce account */\n authorizedPubkey: PublicKey;\n /** Amount of lamports to transfer to the created nonce account */\n lamports: number;\n};\n\n/**\n * Create nonce account with seed system transaction params\n */\nexport type CreateNonceAccountWithSeedParams = {\n /** The account that will transfer lamports to the created nonce account */\n fromPubkey: PublicKey;\n /** Public key of the created nonce account */\n noncePubkey: PublicKey;\n /** Public key to set as authority of the created nonce account */\n authorizedPubkey: PublicKey;\n /** Amount of lamports to transfer to the created nonce account */\n lamports: number;\n /** Base public key to use to derive the address of the nonce account */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the nonce account */\n seed: string;\n};\n\n/**\n * Initialize nonce account system instruction params\n */\nexport type InitializeNonceParams = {\n /** Nonce account which will be initialized */\n noncePubkey: PublicKey;\n /** Public key to set as authority of the initialized nonce account */\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Advance nonce account system instruction params\n */\nexport type AdvanceNonceParams = {\n /** Nonce account */\n noncePubkey: PublicKey;\n /** Public key of the nonce authority */\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Withdraw nonce account system transaction params\n */\nexport type WithdrawNonceParams = {\n /** Nonce account */\n noncePubkey: PublicKey;\n /** Public key of the nonce authority */\n authorizedPubkey: PublicKey;\n /** Public key of the account which will receive the withdrawn nonce account balance */\n toPubkey: PublicKey;\n /** Amount of lamports to withdraw from the nonce account */\n lamports: number;\n};\n\n/**\n * Authorize nonce account system transaction params\n */\nexport type AuthorizeNonceParams = {\n /** Nonce account */\n noncePubkey: PublicKey;\n /** Public key of the current nonce authority */\n authorizedPubkey: PublicKey;\n /** Public key to set as the new nonce authority */\n newAuthorizedPubkey: PublicKey;\n};\n\n/**\n * Allocate account system transaction params\n */\nexport type AllocateParams = {\n /** Account to allocate */\n accountPubkey: PublicKey;\n /** Amount of space in bytes to allocate */\n space: number;\n};\n\n/**\n * Allocate account with seed system transaction params\n */\nexport type AllocateWithSeedParams = {\n /** Account to allocate */\n accountPubkey: PublicKey;\n /** Base public key to use to derive the address of the allocated account */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the allocated account */\n seed: string;\n /** Amount of space in bytes to allocate */\n space: number;\n /** Public key of the program to assign as the owner of the allocated account */\n programId: PublicKey;\n};\n\n/**\n * Assign account with seed system transaction params\n */\nexport type AssignWithSeedParams = {\n /** Public key of the account which will be assigned a new owner */\n accountPubkey: PublicKey;\n /** Base public key to use to derive the address of the assigned account */\n basePubkey: PublicKey;\n /** Seed to use to derive the address of the assigned account */\n seed: string;\n /** Public key of the program to assign as the owner */\n programId: PublicKey;\n};\n\n/**\n * Transfer with seed system transaction params\n */\nexport type TransferWithSeedParams = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Base public key to use to derive the funding account address */\n basePubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: number | bigint;\n /** Seed to use to derive the funding account address */\n seed: string;\n /** Program id to use to derive the funding account address */\n programId: PublicKey;\n};\n\n/** Decoded transfer system transaction instruction */\nexport type DecodedTransferInstruction = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: bigint;\n};\n\n/** Decoded transferWithSeed system transaction instruction */\nexport type DecodedTransferWithSeedInstruction = {\n /** Account that will transfer lamports */\n fromPubkey: PublicKey;\n /** Base public key to use to derive the funding account address */\n basePubkey: PublicKey;\n /** Account that will receive transferred lamports */\n toPubkey: PublicKey;\n /** Amount of lamports to transfer */\n lamports: bigint;\n /** Seed to use to derive the funding account address */\n seed: string;\n /** Program id to use to derive the funding account address */\n programId: PublicKey;\n};\n\n/**\n * System Instruction class\n */\nexport class SystemInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a system instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): SystemInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: SystemInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType as SystemInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error('Instruction type incorrect; not a SystemInstruction');\n }\n\n return type;\n }\n\n /**\n * Decode a create account system instruction and retrieve the instruction params.\n */\n static decodeCreateAccount(\n instruction: TransactionInstruction,\n ): CreateAccountParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {lamports, space, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Create,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n lamports,\n space,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode a transfer system instruction and retrieve the instruction params.\n */\n static decodeTransfer(\n instruction: TransactionInstruction,\n ): DecodedTransferInstruction {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {lamports} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Transfer,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n lamports,\n };\n }\n\n /**\n * Decode a transfer with seed system instruction and retrieve the instruction params.\n */\n static decodeTransferWithSeed(\n instruction: TransactionInstruction,\n ): DecodedTransferWithSeedInstruction {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {lamports, seed, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n basePubkey: instruction.keys[1].pubkey,\n toPubkey: instruction.keys[2].pubkey,\n lamports,\n seed,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode an allocate system instruction and retrieve the instruction params.\n */\n static decodeAllocate(instruction: TransactionInstruction): AllocateParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {space} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Allocate,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n space,\n };\n }\n\n /**\n * Decode an allocate with seed system instruction and retrieve the instruction params.\n */\n static decodeAllocateWithSeed(\n instruction: TransactionInstruction,\n ): AllocateWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {base, seed, space, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n space,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode an assign system instruction and retrieve the instruction params.\n */\n static decodeAssign(instruction: TransactionInstruction): AssignParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.Assign,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode an assign with seed system instruction and retrieve the instruction params.\n */\n static decodeAssignWithSeed(\n instruction: TransactionInstruction,\n ): AssignWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 1);\n\n const {base, seed, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,\n instruction.data,\n );\n\n return {\n accountPubkey: instruction.keys[0].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode a create account with seed system instruction and retrieve the instruction params.\n */\n static decodeCreateWithSeed(\n instruction: TransactionInstruction,\n ): CreateAccountWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {base, seed, lamports, space, programId} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,\n instruction.data,\n );\n\n return {\n fromPubkey: instruction.keys[0].pubkey,\n newAccountPubkey: instruction.keys[1].pubkey,\n basePubkey: new PublicKey(base),\n seed,\n lamports,\n space,\n programId: new PublicKey(programId),\n };\n }\n\n /**\n * Decode a nonce initialize system instruction and retrieve the instruction params.\n */\n static decodeNonceInitialize(\n instruction: TransactionInstruction,\n ): InitializeNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {authorized} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: new PublicKey(authorized),\n };\n }\n\n /**\n * Decode a nonce advance system instruction and retrieve the instruction params.\n */\n static decodeNonceAdvance(\n instruction: TransactionInstruction,\n ): AdvanceNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n };\n }\n\n /**\n * Decode a nonce withdraw system instruction and retrieve the instruction params.\n */\n static decodeNonceWithdraw(\n instruction: TransactionInstruction,\n ): WithdrawNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n\n const {lamports} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports,\n };\n }\n\n /**\n * Decode a nonce authorize system instruction and retrieve the instruction params.\n */\n static decodeNonceAuthorize(\n instruction: TransactionInstruction,\n ): AuthorizeNonceParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {authorized} = decodeData(\n SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,\n instruction.data,\n );\n\n return {\n noncePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[1].pubkey,\n newAuthorizedPubkey: new PublicKey(authorized),\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(SystemProgram.programId)) {\n throw new Error('invalid instruction; programId is not SystemProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\n/**\n * An enumeration of valid SystemInstructionType's\n */\nexport type SystemInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof SystemInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'AdvanceNonceAccount'\n | 'Allocate'\n | 'AllocateWithSeed'\n | 'Assign'\n | 'AssignWithSeed'\n | 'AuthorizeNonceAccount'\n | 'Create'\n | 'CreateWithSeed'\n | 'InitializeNonceAccount'\n | 'Transfer'\n | 'TransferWithSeed'\n | 'WithdrawNonceAccount'\n | 'UpgradeNonceAccount';\n\ntype SystemInstructionInputData = {\n AdvanceNonceAccount: IInstructionInputData;\n Allocate: IInstructionInputData & {\n space: number;\n };\n AllocateWithSeed: IInstructionInputData & {\n base: Uint8Array;\n programId: Uint8Array;\n seed: string;\n space: number;\n };\n Assign: IInstructionInputData & {\n programId: Uint8Array;\n };\n AssignWithSeed: IInstructionInputData & {\n base: Uint8Array;\n seed: string;\n programId: Uint8Array;\n };\n AuthorizeNonceAccount: IInstructionInputData & {\n authorized: Uint8Array;\n };\n Create: IInstructionInputData & {\n lamports: number;\n programId: Uint8Array;\n space: number;\n };\n CreateWithSeed: IInstructionInputData & {\n base: Uint8Array;\n lamports: number;\n programId: Uint8Array;\n seed: string;\n space: number;\n };\n InitializeNonceAccount: IInstructionInputData & {\n authorized: Uint8Array;\n };\n Transfer: IInstructionInputData & {\n lamports: bigint;\n };\n TransferWithSeed: IInstructionInputData & {\n lamports: bigint;\n programId: Uint8Array;\n seed: string;\n };\n WithdrawNonceAccount: IInstructionInputData & {\n lamports: number;\n };\n UpgradeNonceAccount: IInstructionInputData;\n};\n\n/**\n * An enumeration of valid system InstructionType's\n * @internal\n */\nexport const SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in SystemInstructionType]: InstructionType<\n SystemInstructionInputData[Instruction]\n >;\n}>({\n Create: {\n index: 0,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n BufferLayout.ns64('space'),\n Layout.publicKey('programId'),\n ]),\n },\n Assign: {\n index: 1,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('programId'),\n ]),\n },\n Transfer: {\n index: 2,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n u64('lamports'),\n ]),\n },\n CreateWithSeed: {\n index: 3,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('base'),\n Layout.rustString('seed'),\n BufferLayout.ns64('lamports'),\n BufferLayout.ns64('space'),\n Layout.publicKey('programId'),\n ]),\n },\n AdvanceNonceAccount: {\n index: 4,\n layout: BufferLayout.struct<\n SystemInstructionInputData['AdvanceNonceAccount']\n >([BufferLayout.u32('instruction')]),\n },\n WithdrawNonceAccount: {\n index: 5,\n layout: BufferLayout.struct<\n SystemInstructionInputData['WithdrawNonceAccount']\n >([BufferLayout.u32('instruction'), BufferLayout.ns64('lamports')]),\n },\n InitializeNonceAccount: {\n index: 6,\n layout: BufferLayout.struct<\n SystemInstructionInputData['InitializeNonceAccount']\n >([BufferLayout.u32('instruction'), Layout.publicKey('authorized')]),\n },\n AuthorizeNonceAccount: {\n index: 7,\n layout: BufferLayout.struct<\n SystemInstructionInputData['AuthorizeNonceAccount']\n >([BufferLayout.u32('instruction'), Layout.publicKey('authorized')]),\n },\n Allocate: {\n index: 8,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('space'),\n ]),\n },\n AllocateWithSeed: {\n index: 9,\n layout: BufferLayout.struct(\n [\n BufferLayout.u32('instruction'),\n Layout.publicKey('base'),\n Layout.rustString('seed'),\n BufferLayout.ns64('space'),\n Layout.publicKey('programId'),\n ],\n ),\n },\n AssignWithSeed: {\n index: 10,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('base'),\n Layout.rustString('seed'),\n Layout.publicKey('programId'),\n ]),\n },\n TransferWithSeed: {\n index: 11,\n layout: BufferLayout.struct(\n [\n BufferLayout.u32('instruction'),\n u64('lamports'),\n Layout.rustString('seed'),\n Layout.publicKey('programId'),\n ],\n ),\n },\n UpgradeNonceAccount: {\n index: 12,\n layout: BufferLayout.struct<\n SystemInstructionInputData['UpgradeNonceAccount']\n >([BufferLayout.u32('instruction')]),\n },\n});\n\n/**\n * Factory class for transactions to interact with the System program\n */\nexport class SystemProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the System program\n */\n static programId: PublicKey = new PublicKey(\n '11111111111111111111111111111111',\n );\n\n /**\n * Generate a transaction instruction that creates a new account\n */\n static createAccount(params: CreateAccountParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;\n const data = encodeData(type, {\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer()),\n });\n\n return new TransactionInstruction({\n keys: [\n {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n {pubkey: params.newAccountPubkey, isSigner: true, isWritable: true},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that transfers lamports from one account to another\n */\n static transfer(\n params: TransferParams | TransferWithSeedParams,\n ): TransactionInstruction {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;\n data = encodeData(type, {\n lamports: BigInt(params.lamports),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [\n {pubkey: params.fromPubkey, isSigner: false, isWritable: true},\n {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n ];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;\n data = encodeData(type, {lamports: BigInt(params.lamports)});\n keys = [\n {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n ];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that assigns an account to a program\n */\n static assign(\n params: AssignParams | AssignWithSeedParams,\n ): TransactionInstruction {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [\n {pubkey: params.accountPubkey, isSigner: false, isWritable: true},\n {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n ];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;\n data = encodeData(type, {\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that creates a new account at\n * an address generated with `from`, a seed, and programId\n */\n static createAccountWithSeed(\n params: CreateAccountWithSeedParams,\n ): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;\n const data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n lamports: params.lamports,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer()),\n });\n let keys = [\n {pubkey: params.fromPubkey, isSigner: true, isWritable: true},\n {pubkey: params.newAccountPubkey, isSigner: false, isWritable: true},\n ];\n if (!params.basePubkey.equals(params.fromPubkey)) {\n keys.push({\n pubkey: params.basePubkey,\n isSigner: true,\n isWritable: false,\n });\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction that creates a new Nonce account\n */\n static createNonceAccount(\n params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams,\n ): Transaction {\n const transaction = new Transaction();\n if ('basePubkey' in params && 'seed' in params) {\n transaction.add(\n SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId,\n }),\n );\n } else {\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.noncePubkey,\n lamports: params.lamports,\n space: NONCE_ACCOUNT_LENGTH,\n programId: this.programId,\n }),\n );\n }\n\n const initParams = {\n noncePubkey: params.noncePubkey,\n authorizedPubkey: params.authorizedPubkey,\n };\n\n transaction.add(this.nonceInitialize(initParams));\n return transaction;\n }\n\n /**\n * Generate an instruction to initialize a Nonce account\n */\n static nonceInitialize(\n params: InitializeNonceParams,\n ): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.authorizedPubkey.toBuffer()),\n });\n const instructionData = {\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate an instruction to advance the nonce in a Nonce account\n */\n static nonceAdvance(params: AdvanceNonceParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;\n const data = encodeData(type);\n const instructionData = {\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction instruction that withdraws lamports from a Nonce account\n */\n static nonceWithdraw(params: WithdrawNonceParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;\n const data = encodeData(type, {lamports: params.lamports});\n\n return new TransactionInstruction({\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {pubkey: params.toPubkey, isSigner: false, isWritable: true},\n {\n pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: SYSVAR_RENT_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that authorizes a new PublicKey as the authority\n * on a Nonce account.\n */\n static nonceAuthorize(params: AuthorizeNonceParams): TransactionInstruction {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;\n const data = encodeData(type, {\n authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()),\n });\n\n return new TransactionInstruction({\n keys: [\n {pubkey: params.noncePubkey, isSigner: false, isWritable: true},\n {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction instruction that allocates space in an account without funding\n */\n static allocate(\n params: AllocateParams | AllocateWithSeedParams,\n ): TransactionInstruction {\n let data;\n let keys;\n if ('basePubkey' in params) {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;\n data = encodeData(type, {\n base: toBuffer(params.basePubkey.toBuffer()),\n seed: params.seed,\n space: params.space,\n programId: toBuffer(params.programId.toBuffer()),\n });\n keys = [\n {pubkey: params.accountPubkey, isSigner: false, isWritable: true},\n {pubkey: params.basePubkey, isSigner: true, isWritable: false},\n ];\n } else {\n const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;\n data = encodeData(type, {\n space: params.space,\n });\n keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];\n }\n\n return new TransactionInstruction({\n keys,\n programId: this.programId,\n data,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {PublicKey} from './publickey';\nimport {Transaction, PACKET_DATA_SIZE} from './transaction';\nimport {MS_PER_SLOT} from './timing';\nimport {SYSVAR_RENT_PUBKEY} from './sysvar';\nimport {sendAndConfirmTransaction} from './utils/send-and-confirm-transaction';\nimport {sleep} from './utils/sleep';\nimport type {Connection} from './connection';\nimport type {Signer} from './keypair';\nimport {SystemProgram} from './programs/system';\nimport {IInstructionInputData} from './instruction';\n\n// Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the\n// rest of the Transaction fields\n//\n// TODO: replace 300 with a proper constant for the size of the other\n// Transaction fields\nconst CHUNK_SIZE = PACKET_DATA_SIZE - 300;\n\n/**\n * Program loader interface\n */\nexport class Loader {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Amount of program data placed in each load Transaction\n */\n static chunkSize: number = CHUNK_SIZE;\n\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength: number): number {\n return (\n 2 * // Every transaction requires two signatures (payer + program)\n (Math.ceil(dataLength / Loader.chunkSize) +\n 1 + // Add one for Create transaction\n 1) // Add one for Finalize transaction\n );\n }\n\n /**\n * Loads a generic program\n *\n * @param connection The connection to use\n * @param payer System account that pays to load the program\n * @param program Account to load the program into\n * @param programId Public key that identifies the loader\n * @param data Program octets\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static async load(\n connection: Connection,\n payer: Signer,\n program: Signer,\n programId: PublicKey,\n data: Buffer | Uint8Array | Array,\n ): Promise {\n {\n const balanceNeeded = await connection.getMinimumBalanceForRentExemption(\n data.length,\n );\n\n // Fetch program account info to check if it has already been created\n const programInfo = await connection.getAccountInfo(\n program.publicKey,\n 'confirmed',\n );\n\n let transaction: Transaction | null = null;\n if (programInfo !== null) {\n if (programInfo.executable) {\n console.error('Program load failed, account is already executable');\n return false;\n }\n\n if (programInfo.data.length !== data.length) {\n transaction = transaction || new Transaction();\n transaction.add(\n SystemProgram.allocate({\n accountPubkey: program.publicKey,\n space: data.length,\n }),\n );\n }\n\n if (!programInfo.owner.equals(programId)) {\n transaction = transaction || new Transaction();\n transaction.add(\n SystemProgram.assign({\n accountPubkey: program.publicKey,\n programId,\n }),\n );\n }\n\n if (programInfo.lamports < balanceNeeded) {\n transaction = transaction || new Transaction();\n transaction.add(\n SystemProgram.transfer({\n fromPubkey: payer.publicKey,\n toPubkey: program.publicKey,\n lamports: balanceNeeded - programInfo.lamports,\n }),\n );\n }\n } else {\n transaction = new Transaction().add(\n SystemProgram.createAccount({\n fromPubkey: payer.publicKey,\n newAccountPubkey: program.publicKey,\n lamports: balanceNeeded > 0 ? balanceNeeded : 1,\n space: data.length,\n programId,\n }),\n );\n }\n\n // If the account is already created correctly, skip this step\n // and proceed directly to loading instructions\n if (transaction !== null) {\n await sendAndConfirmTransaction(\n connection,\n transaction,\n [payer, program],\n {\n commitment: 'confirmed',\n },\n );\n }\n }\n\n const dataLayout = BufferLayout.struct<\n Readonly<{\n bytes: number[];\n bytesLength: number;\n bytesLengthPadding: number;\n instruction: number;\n offset: number;\n }>\n >([\n BufferLayout.u32('instruction'),\n BufferLayout.u32('offset'),\n BufferLayout.u32('bytesLength'),\n BufferLayout.u32('bytesLengthPadding'),\n BufferLayout.seq(\n BufferLayout.u8('byte'),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'bytes',\n ),\n ]);\n\n const chunkSize = Loader.chunkSize;\n let offset = 0;\n let array = data;\n let transactions = [];\n while (array.length > 0) {\n const bytes = array.slice(0, chunkSize);\n const data = Buffer.alloc(chunkSize + 16);\n dataLayout.encode(\n {\n instruction: 0, // Load instruction\n offset,\n bytes: bytes as number[],\n bytesLength: 0,\n bytesLengthPadding: 0,\n },\n data,\n );\n\n const transaction = new Transaction().add({\n keys: [{pubkey: program.publicKey, isSigner: true, isWritable: true}],\n programId,\n data,\n });\n transactions.push(\n sendAndConfirmTransaction(connection, transaction, [payer, program], {\n commitment: 'confirmed',\n }),\n );\n\n // Delay between sends in an attempt to reduce rate limit errors\n if (connection._rpcEndpoint.includes('solana.com')) {\n const REQUESTS_PER_SECOND = 4;\n await sleep(1000 / REQUESTS_PER_SECOND);\n }\n\n offset += chunkSize;\n array = array.slice(chunkSize);\n }\n await Promise.all(transactions);\n\n // Finalize the account loaded with program data for execution\n {\n const dataLayout = BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]);\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n instruction: 1, // Finalize instruction\n },\n data,\n );\n\n const transaction = new Transaction().add({\n keys: [\n {pubkey: program.publicKey, isSigner: true, isWritable: true},\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n ],\n programId,\n data,\n });\n const deployCommitment = 'processed';\n const finalizeSignature = await connection.sendTransaction(\n transaction,\n [payer, program],\n {preflightCommitment: deployCommitment},\n );\n const {context, value} = await connection.confirmTransaction(\n {\n signature: finalizeSignature,\n lastValidBlockHeight: transaction.lastValidBlockHeight!,\n blockhash: transaction.recentBlockhash!,\n },\n deployCommitment,\n );\n if (value.err) {\n throw new Error(\n `Transaction ${finalizeSignature} failed (${JSON.stringify(value)})`,\n );\n }\n // We prevent programs from being usable until the slot after their deployment.\n // See https://github.com/solana-labs/solana/pull/29654\n while (\n true // eslint-disable-line no-constant-condition\n ) {\n try {\n const currentSlot = await connection.getSlot({\n commitment: deployCommitment,\n });\n if (currentSlot > context.slot) {\n break;\n }\n } catch {\n /* empty */\n }\n await new Promise(resolve =>\n setTimeout(resolve, Math.round(MS_PER_SLOT / 2)),\n );\n }\n }\n\n // success\n return true;\n }\n}\n","import type {Buffer} from 'buffer';\n\nimport {PublicKey} from './publickey';\nimport {Loader} from './loader';\nimport type {Connection} from './connection';\nimport type {Signer} from './keypair';\n\n/**\n * @deprecated Deprecated since Solana v1.17.20.\n */\nexport const BPF_LOADER_PROGRAM_ID = new PublicKey(\n 'BPFLoader2111111111111111111111111111111111',\n);\n\n/**\n * Factory class for transactions to interact with a program loader\n *\n * @deprecated Deprecated since Solana v1.17.20.\n */\nexport class BpfLoader {\n /**\n * Minimum number of signatures required to load a program not including\n * retries\n *\n * Can be used to calculate transaction fees\n */\n static getMinNumSignatures(dataLength: number): number {\n return Loader.getMinNumSignatures(dataLength);\n }\n\n /**\n * Load a SBF program\n *\n * @param connection The connection to use\n * @param payer Account that will pay program loading fees\n * @param program Account to load the program into\n * @param elf The entire ELF containing the SBF program\n * @param loaderProgramId The program id of the BPF loader to use\n * @return true if program was loaded successfully, false if program was already loaded\n */\n static load(\n connection: Connection,\n payer: Signer,\n program: Signer,\n elf: Buffer | Uint8Array | Array,\n loaderProgramId: PublicKey,\n ): Promise {\n return Loader.load(connection, payer, program, loaderProgramId, elf);\n }\n}\n","var objToString = Object.prototype.toString;\nvar objKeys = Object.keys || function(obj) {\n\t\tvar keys = [];\n\t\tfor (var name in obj) {\n\t\t\tkeys.push(name);\n\t\t}\n\t\treturn keys;\n\t};\n\nfunction stringify(val, isArrayProp) {\n\tvar i, max, str, keys, key, propVal, toStr;\n\tif (val === true) {\n\t\treturn \"true\";\n\t}\n\tif (val === false) {\n\t\treturn \"false\";\n\t}\n\tswitch (typeof val) {\n\t\tcase \"object\":\n\t\t\tif (val === null) {\n\t\t\t\treturn null;\n\t\t\t} else if (val.toJSON && typeof val.toJSON === \"function\") {\n\t\t\t\treturn stringify(val.toJSON(), isArrayProp);\n\t\t\t} else {\n\t\t\t\ttoStr = objToString.call(val);\n\t\t\t\tif (toStr === \"[object Array]\") {\n\t\t\t\t\tstr = '[';\n\t\t\t\t\tmax = val.length - 1;\n\t\t\t\t\tfor(i = 0; i < max; i++) {\n\t\t\t\t\t\tstr += stringify(val[i], true) + ',';\n\t\t\t\t\t}\n\t\t\t\t\tif (max > -1) {\n\t\t\t\t\t\tstr += stringify(val[i], true);\n\t\t\t\t\t}\n\t\t\t\t\treturn str + ']';\n\t\t\t\t} else if (toStr === \"[object Object]\") {\n\t\t\t\t\t// only object is left\n\t\t\t\t\tkeys = objKeys(val).sort();\n\t\t\t\t\tmax = keys.length;\n\t\t\t\t\tstr = \"\";\n\t\t\t\t\ti = 0;\n\t\t\t\t\twhile (i < max) {\n\t\t\t\t\t\tkey = keys[i];\n\t\t\t\t\t\tpropVal = stringify(val[key], false);\n\t\t\t\t\t\tif (propVal !== undefined) {\n\t\t\t\t\t\t\tif (str) {\n\t\t\t\t\t\t\t\tstr += ',';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstr += JSON.stringify(key) + ':' + propVal;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn '{' + str + '}';\n\t\t\t\t} else {\n\t\t\t\t\treturn JSON.stringify(val);\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"function\":\n\t\tcase \"undefined\":\n\t\t\treturn isArrayProp ? null : undefined;\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(val);\n\t\tdefault:\n\t\t\treturn isFinite(val) ? val : null;\n\t}\n}\n\nmodule.exports = function(val) {\n\tvar returnVal = stringify(val, false);\n\tif (returnVal !== undefined) {\n\t\treturn ''+ returnVal;\n\t}\n};\n","const MINIMUM_SLOT_PER_EPOCH = 32;\n\n// Returns the number of trailing zeros in the binary representation of self.\nfunction trailingZeros(n: number) {\n let trailingZeros = 0;\n while (n > 1) {\n n /= 2;\n trailingZeros++;\n }\n return trailingZeros;\n}\n\n// Returns the smallest power of two greater than or equal to n\nfunction nextPowerOfTwo(n: number) {\n if (n === 0) return 1;\n n--;\n n |= n >> 1;\n n |= n >> 2;\n n |= n >> 4;\n n |= n >> 8;\n n |= n >> 16;\n n |= n >> 32;\n return n + 1;\n}\n\n/**\n * Epoch schedule\n * (see https://docs.solana.com/terminology#epoch)\n * Can be retrieved with the {@link Connection.getEpochSchedule} method\n */\nexport class EpochSchedule {\n /** The maximum number of slots in each epoch */\n public slotsPerEpoch: number;\n /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */\n public leaderScheduleSlotOffset: number;\n /** Indicates whether epochs start short and grow */\n public warmup: boolean;\n /** The first epoch with `slotsPerEpoch` slots */\n public firstNormalEpoch: number;\n /** The first slot of `firstNormalEpoch` */\n public firstNormalSlot: number;\n\n constructor(\n slotsPerEpoch: number,\n leaderScheduleSlotOffset: number,\n warmup: boolean,\n firstNormalEpoch: number,\n firstNormalSlot: number,\n ) {\n this.slotsPerEpoch = slotsPerEpoch;\n this.leaderScheduleSlotOffset = leaderScheduleSlotOffset;\n this.warmup = warmup;\n this.firstNormalEpoch = firstNormalEpoch;\n this.firstNormalSlot = firstNormalSlot;\n }\n\n getEpoch(slot: number): number {\n return this.getEpochAndSlotIndex(slot)[0];\n }\n\n getEpochAndSlotIndex(slot: number): [number, number] {\n if (slot < this.firstNormalSlot) {\n const epoch =\n trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) -\n trailingZeros(MINIMUM_SLOT_PER_EPOCH) -\n 1;\n\n const epochLen = this.getSlotsInEpoch(epoch);\n const slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH);\n return [epoch, slotIndex];\n } else {\n const normalSlotIndex = slot - this.firstNormalSlot;\n const normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch);\n const epoch = this.firstNormalEpoch + normalEpochIndex;\n const slotIndex = normalSlotIndex % this.slotsPerEpoch;\n return [epoch, slotIndex];\n }\n }\n\n getFirstSlotInEpoch(epoch: number): number {\n if (epoch <= this.firstNormalEpoch) {\n return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH;\n } else {\n return (\n (epoch - this.firstNormalEpoch) * this.slotsPerEpoch +\n this.firstNormalSlot\n );\n }\n }\n\n getLastSlotInEpoch(epoch: number): number {\n return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1;\n }\n\n getSlotsInEpoch(epoch: number) {\n if (epoch < this.firstNormalEpoch) {\n return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH));\n } else {\n return this.slotsPerEpoch;\n }\n }\n}\n","export const Headers: typeof globalThis.Headers = globalThis.Headers;\nexport const Request: typeof globalThis.Request = globalThis.Request;\nexport const Response: typeof globalThis.Response = globalThis.Response;\nexport default globalThis.fetch;\n","import {\n CommonClient,\n ICommonWebSocket,\n IWSClientAdditionalOptions,\n NodeWebSocketType,\n NodeWebSocketTypeOptions,\n WebSocket as createRpc,\n} from 'rpc-websockets';\n\ninterface IHasReadyState {\n readyState: WebSocket['readyState'];\n}\n\nexport default class RpcWebSocketClient extends CommonClient {\n private underlyingSocket: IHasReadyState | undefined;\n constructor(\n address?: string,\n options?: IWSClientAdditionalOptions & NodeWebSocketTypeOptions,\n generate_request_id?: (\n method: string,\n params: object | Array,\n ) => number,\n ) {\n const webSocketFactory = (url: string) => {\n const rpc = createRpc(url, {\n autoconnect: true,\n max_reconnects: 5,\n reconnect: true,\n reconnect_interval: 1000,\n ...options,\n });\n if ('socket' in rpc) {\n this.underlyingSocket = rpc.socket as ReturnType;\n } else {\n this.underlyingSocket = rpc as NodeWebSocketType;\n }\n return rpc as ICommonWebSocket;\n };\n super(webSocketFactory, address, options, generate_request_id);\n }\n call(\n ...args: Parameters\n ): ReturnType {\n const readyState = this.underlyingSocket?.readyState;\n if (readyState === 1 /* WebSocket.OPEN */) {\n return super.call(...args);\n }\n return Promise.reject(\n new Error(\n 'Tried to call a JSON-RPC method `' +\n args[0] +\n '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' +\n readyState +\n ')',\n ),\n );\n }\n notify(\n ...args: Parameters\n ): ReturnType {\n const readyState = this.underlyingSocket?.readyState;\n if (readyState === 1 /* WebSocket.OPEN */) {\n return super.notify(...args);\n }\n return Promise.reject(\n new Error(\n 'Tried to send a JSON-RPC notification `' +\n args[0] +\n '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' +\n readyState +\n ')',\n ),\n );\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport assert from '../../utils/assert';\nimport * as Layout from '../../layout';\nimport {PublicKey} from '../../publickey';\nimport {u64} from '../../utils/bigint';\nimport {decodeData} from '../../account-data';\n\nexport type AddressLookupTableState = {\n deactivationSlot: bigint;\n lastExtendedSlot: number;\n lastExtendedSlotStartIndex: number;\n authority?: PublicKey;\n addresses: Array;\n};\n\nexport type AddressLookupTableAccountArgs = {\n key: PublicKey;\n state: AddressLookupTableState;\n};\n\n/// The serialized size of lookup table metadata\nconst LOOKUP_TABLE_META_SIZE = 56;\n\nexport class AddressLookupTableAccount {\n key: PublicKey;\n state: AddressLookupTableState;\n\n constructor(args: AddressLookupTableAccountArgs) {\n this.key = args.key;\n this.state = args.state;\n }\n\n isActive(): boolean {\n const U64_MAX = BigInt('0xffffffffffffffff');\n return this.state.deactivationSlot === U64_MAX;\n }\n\n static deserialize(accountData: Uint8Array): AddressLookupTableState {\n const meta = decodeData(LookupTableMetaLayout, accountData);\n\n const serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE;\n assert(serializedAddressesLen >= 0, 'lookup table is invalid');\n assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid');\n\n const numSerializedAddresses = serializedAddressesLen / 32;\n const {addresses} = BufferLayout.struct<{addresses: Array}>([\n BufferLayout.seq(Layout.publicKey(), numSerializedAddresses, 'addresses'),\n ]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE));\n\n return {\n deactivationSlot: meta.deactivationSlot,\n lastExtendedSlot: meta.lastExtendedSlot,\n lastExtendedSlotStartIndex: meta.lastExtendedStartIndex,\n authority:\n meta.authority.length !== 0\n ? new PublicKey(meta.authority[0])\n : undefined,\n addresses: addresses.map(address => new PublicKey(address)),\n };\n }\n}\n\nconst LookupTableMetaLayout = {\n index: 1,\n layout: BufferLayout.struct<{\n typeIndex: number;\n deactivationSlot: bigint;\n lastExtendedSlot: number;\n lastExtendedStartIndex: number;\n authority: Array;\n }>([\n BufferLayout.u32('typeIndex'),\n u64('deactivationSlot'),\n BufferLayout.nu64('lastExtendedSlot'),\n BufferLayout.u8('lastExtendedStartIndex'),\n BufferLayout.u8(), // option\n BufferLayout.seq(\n Layout.publicKey(),\n BufferLayout.offset(BufferLayout.u8(), -1),\n 'authority',\n ),\n ]),\n};\n","import * as BufferLayout from '@solana/buffer-layout';\n\nexport interface IAccountStateData {\n readonly typeIndex: number;\n}\n\n/**\n * @internal\n */\nexport type AccountType = {\n /** The account type index (from solana upstream program) */\n index: number;\n /** The BufferLayout to use to build data */\n layout: BufferLayout.Layout;\n};\n\n/**\n * Decode account data buffer using an AccountType\n * @internal\n */\nexport function decodeData(\n type: AccountType,\n data: Uint8Array,\n): TAccountStateData {\n let decoded: TAccountStateData;\n try {\n decoded = type.layout.decode(data);\n } catch (err) {\n throw new Error('invalid instruction; ' + err);\n }\n\n if (decoded.typeIndex !== type.index) {\n throw new Error(\n `invalid account data; account type mismatch ${decoded.typeIndex} != ${type.index}`,\n );\n }\n\n return decoded;\n}\n","const URL_RE = /^[^:]+:\\/\\/([^:[]+|\\[[^\\]]+\\])(:\\d+)?(.*)/i;\n\nexport function makeWebsocketUrl(endpoint: string) {\n const matches = endpoint.match(URL_RE);\n if (matches == null) {\n throw TypeError(`Failed to validate endpoint URL \\`${endpoint}\\``);\n }\n const [\n _, // eslint-disable-line @typescript-eslint/no-unused-vars\n hostish,\n portWithColon,\n rest,\n ] = matches;\n const protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:';\n const startPort =\n portWithColon == null ? null : parseInt(portWithColon.slice(1), 10);\n const websocketPort =\n // Only shift the port by +1 as a convention for ws(s) only if given endpoint\n // is explicitly specifying the endpoint port (HTTP-based RPC), assuming\n // we're directly trying to connect to agave-validator's ws listening port.\n // When the endpoint omits the port, we're connecting to the protocol\n // default ports: http(80) or https(443) and it's assumed we're behind a reverse\n // proxy which manages WebSocket upgrade and backend port redirection.\n startPort == null ? '' : `:${startPort + 1}`;\n return `${protocol}//${hostish}${websocketPort}${rest}`;\n}\n","import HttpKeepAliveAgent, {\n HttpsAgent as HttpsKeepAliveAgent,\n} from 'agentkeepalive';\nimport bs58 from 'bs58';\nimport {Buffer} from 'buffer';\n// @ts-ignore\nimport fastStableStringify from 'fast-stable-stringify';\nimport type {Agent as NodeHttpAgent} from 'http';\nimport {Agent as NodeHttpsAgent} from 'https';\nimport {\n type as pick,\n number,\n string,\n array,\n boolean,\n literal,\n record,\n union,\n optional,\n nullable,\n coerce,\n instance,\n create,\n tuple,\n unknown,\n any,\n} from 'superstruct';\nimport type {Struct} from 'superstruct';\nimport RpcClient from 'jayson/lib/client/browser';\nimport {JSONRPCError} from 'jayson';\n\nimport {EpochSchedule} from './epoch-schedule';\nimport {SendTransactionError, SolanaJSONRPCError} from './errors';\nimport fetchImpl from './fetch-impl';\nimport {DurableNonce, NonceAccount} from './nonce-account';\nimport {PublicKey} from './publickey';\nimport {Signer} from './keypair';\nimport RpcWebSocketClient from './rpc-websocket';\nimport {MS_PER_SLOT} from './timing';\nimport {\n Transaction,\n TransactionStatus,\n TransactionVersion,\n VersionedTransaction,\n} from './transaction';\nimport {Message, MessageHeader, MessageV0, VersionedMessage} from './message';\nimport {AddressLookupTableAccount} from './programs/address-lookup-table/state';\nimport assert from './utils/assert';\nimport {sleep} from './utils/sleep';\nimport {toBuffer} from './utils/to-buffer';\nimport {\n TransactionExpiredBlockheightExceededError,\n TransactionExpiredNonceInvalidError,\n TransactionExpiredTimeoutError,\n} from './transaction/expiry-custom-errors';\nimport {makeWebsocketUrl} from './utils/makeWebsocketUrl';\nimport type {Blockhash} from './blockhash';\nimport type {FeeCalculator} from './fee-calculator';\nimport type {TransactionSignature} from './transaction';\nimport type {CompiledInstruction} from './message';\n\nconst PublicKeyFromString = coerce(\n instance(PublicKey),\n string(),\n value => new PublicKey(value),\n);\n\nconst RawAccountDataResult = tuple([string(), literal('base64')]);\n\nconst BufferFromRawAccountData = coerce(\n instance(Buffer),\n RawAccountDataResult,\n value => Buffer.from(value[0], 'base64'),\n);\n\n/**\n * Attempt to use a recent blockhash for up to 30 seconds\n * @internal\n */\nexport const BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000;\n\n/**\n * HACK.\n * Copied from rpc-websockets/dist/lib/client.\n * Otherwise, `yarn build` fails with:\n * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d\n */\ninterface IWSRequestParams {\n [x: string]: any;\n [x: number]: any;\n}\n\ntype ClientSubscriptionId = number;\n/** @internal */ type ServerSubscriptionId = number;\n/** @internal */ type SubscriptionConfigHash = string;\n/** @internal */ type SubscriptionDisposeFn = () => Promise;\n/** @internal */ type SubscriptionStateChangeCallback = (\n nextState: StatefulSubscription['state'],\n) => void;\n/** @internal */ type SubscriptionStateChangeDisposeFn = () => void;\n/**\n * @internal\n * Every subscription contains the args used to open the subscription with\n * the server, and a list of callers interested in notifications.\n */\ntype BaseSubscription = Readonly<{\n args: IWSRequestParams;\n callbacks: Set['callback']>;\n}>;\n/**\n * @internal\n * A subscription may be in various states of connectedness. Only when it is\n * fully connected will it have a server subscription id associated with it.\n * This id can be returned to the server to unsubscribe the client entirely.\n */\ntype StatefulSubscription = Readonly<\n // New subscriptions that have not yet been\n // sent to the server start in this state.\n | {\n state: 'pending';\n }\n // These subscriptions have been sent to the server\n // and are waiting for the server to acknowledge them.\n | {\n state: 'subscribing';\n }\n // These subscriptions have been acknowledged by the\n // server and have been assigned server subscription ids.\n | {\n serverSubscriptionId: ServerSubscriptionId;\n state: 'subscribed';\n }\n // These subscriptions are intended to be torn down and\n // are waiting on an acknowledgement from the server.\n | {\n serverSubscriptionId: ServerSubscriptionId;\n state: 'unsubscribing';\n }\n // The request to tear down these subscriptions has been\n // acknowledged by the server. The `serverSubscriptionId`\n // is the id of the now-dead subscription.\n | {\n serverSubscriptionId: ServerSubscriptionId;\n state: 'unsubscribed';\n }\n>;\n/**\n * A type that encapsulates a subscription's RPC method\n * names and notification (callback) signature.\n */\ntype SubscriptionConfig = Readonly<\n | {\n callback: AccountChangeCallback;\n method: 'accountSubscribe';\n unsubscribeMethod: 'accountUnsubscribe';\n }\n | {\n callback: LogsCallback;\n method: 'logsSubscribe';\n unsubscribeMethod: 'logsUnsubscribe';\n }\n | {\n callback: ProgramAccountChangeCallback;\n method: 'programSubscribe';\n unsubscribeMethod: 'programUnsubscribe';\n }\n | {\n callback: RootChangeCallback;\n method: 'rootSubscribe';\n unsubscribeMethod: 'rootUnsubscribe';\n }\n | {\n callback: SignatureSubscriptionCallback;\n method: 'signatureSubscribe';\n unsubscribeMethod: 'signatureUnsubscribe';\n }\n | {\n callback: SlotChangeCallback;\n method: 'slotSubscribe';\n unsubscribeMethod: 'slotUnsubscribe';\n }\n | {\n callback: SlotUpdateCallback;\n method: 'slotsUpdatesSubscribe';\n unsubscribeMethod: 'slotsUpdatesUnsubscribe';\n }\n>;\n/**\n * @internal\n * Utility type that keeps tagged unions intact while omitting properties.\n */\ntype DistributiveOmit = T extends unknown\n ? Omit\n : never;\n/**\n * @internal\n * This type represents a single subscribable 'topic.' It's made up of:\n *\n * - The args used to open the subscription with the server,\n * - The state of the subscription, in terms of its connectedness, and\n * - The set of callbacks to call when the server publishes notifications\n *\n * This record gets indexed by `SubscriptionConfigHash` and is used to\n * set up subscriptions, fan out notifications, and track subscription state.\n */\ntype Subscription = BaseSubscription &\n StatefulSubscription &\n DistributiveOmit;\n\ntype RpcRequest = (methodName: string, args: Array) => Promise;\n\ntype RpcBatchRequest = (requests: RpcParams[]) => Promise;\n\n/**\n * @internal\n */\nexport type RpcParams = {\n methodName: string;\n args: Array;\n};\n\nexport type TokenAccountsFilter =\n | {\n mint: PublicKey;\n }\n | {\n programId: PublicKey;\n };\n\n/**\n * Extra contextual information for RPC responses\n */\nexport type Context = {\n slot: number;\n};\n\n/**\n * Options for sending transactions\n */\nexport type SendOptions = {\n /** disable transaction verification step */\n skipPreflight?: boolean;\n /** preflight commitment level */\n preflightCommitment?: Commitment;\n /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n maxRetries?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Options for confirming transactions\n */\nexport type ConfirmOptions = {\n /** disable transaction verification step */\n skipPreflight?: boolean;\n /** desired commitment level */\n commitment?: Commitment;\n /** preflight commitment level */\n preflightCommitment?: Commitment;\n /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n maxRetries?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Options for getConfirmedSignaturesForAddress2\n */\nexport type ConfirmedSignaturesForAddress2Options = {\n /**\n * Start searching backwards from this transaction signature.\n * @remarks If not provided the search starts from the highest max confirmed block.\n */\n before?: TransactionSignature;\n /** Search until this transaction signature is reached, if found before `limit`. */\n until?: TransactionSignature;\n /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */\n limit?: number;\n};\n\n/**\n * Options for getSignaturesForAddress\n */\nexport type SignaturesForAddressOptions = {\n /**\n * Start searching backwards from this transaction signature.\n * @remarks If not provided the search starts from the highest max confirmed block.\n */\n before?: TransactionSignature;\n /** Search until this transaction signature is reached, if found before `limit`. */\n until?: TransactionSignature;\n /** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */\n limit?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * RPC Response with extra contextual information\n */\nexport type RpcResponseAndContext = {\n /** response context */\n context: Context;\n /** response value */\n value: T;\n};\n\nexport type BlockhashWithExpiryBlockHeight = Readonly<{\n blockhash: Blockhash;\n lastValidBlockHeight: number;\n}>;\n\n/**\n * A strategy for confirming transactions that uses the last valid\n * block height for a given blockhash to check for transaction expiration.\n */\nexport type BlockheightBasedTransactionConfirmationStrategy =\n BaseTransactionConfirmationStrategy & BlockhashWithExpiryBlockHeight;\n\n/**\n * A strategy for confirming durable nonce transactions.\n */\nexport type DurableNonceTransactionConfirmationStrategy =\n BaseTransactionConfirmationStrategy & {\n /**\n * The lowest slot at which to fetch the nonce value from the\n * nonce account. This should be no lower than the slot at\n * which the last-known value of the nonce was fetched.\n */\n minContextSlot: number;\n /**\n * The account where the current value of the nonce is stored.\n */\n nonceAccountPubkey: PublicKey;\n /**\n * The nonce value that was used to sign the transaction\n * for which confirmation is being sought.\n */\n nonceValue: DurableNonce;\n };\n\n/**\n * Properties shared by all transaction confirmation strategies\n */\nexport type BaseTransactionConfirmationStrategy = Readonly<{\n /** A signal that, when aborted, cancels any outstanding transaction confirmation operations */\n abortSignal?: AbortSignal;\n signature: TransactionSignature;\n}>;\n\n/**\n * This type represents all transaction confirmation strategies\n */\nexport type TransactionConfirmationStrategy =\n | BlockheightBasedTransactionConfirmationStrategy\n | DurableNonceTransactionConfirmationStrategy;\n\n/* @internal */\nfunction assertEndpointUrl(putativeUrl: string) {\n if (/^https?:/.test(putativeUrl) === false) {\n throw new TypeError('Endpoint URL must start with `http:` or `https:`.');\n }\n return putativeUrl;\n}\n\n/** @internal */\nfunction extractCommitmentFromConfig(\n commitmentOrConfig?: Commitment | ({commitment?: Commitment} & TConfig),\n) {\n let commitment: Commitment | undefined;\n let config: Omit | undefined;\n if (typeof commitmentOrConfig === 'string') {\n commitment = commitmentOrConfig;\n } else if (commitmentOrConfig) {\n const {commitment: specifiedCommitment, ...specifiedConfig} =\n commitmentOrConfig;\n commitment = specifiedCommitment;\n config = specifiedConfig;\n }\n return {commitment, config};\n}\n\n/**\n * @internal\n */\nfunction applyDefaultMemcmpEncodingToFilters(\n filters: GetProgramAccountsFilter[],\n): GetProgramAccountsFilter[] {\n return filters.map(filter =>\n 'memcmp' in filter\n ? {\n ...filter,\n memcmp: {\n ...filter.memcmp,\n encoding: filter.memcmp.encoding ?? 'base58',\n },\n }\n : filter,\n );\n}\n\n/**\n * @internal\n */\nfunction createRpcResult(result: Struct) {\n return union([\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n result,\n }),\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n error: pick({\n code: unknown(),\n message: string(),\n data: optional(any()),\n }),\n }),\n ]);\n}\n\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nfunction jsonRpcResult(schema: Struct) {\n return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n if ('error' in value) {\n return value;\n } else {\n return {\n ...value,\n result: create(value.result, schema),\n };\n }\n });\n}\n\n/**\n * @internal\n */\nfunction jsonRpcResultAndContext(value: Struct) {\n return jsonRpcResult(\n pick({\n context: pick({\n slot: number(),\n }),\n value,\n }),\n );\n}\n\n/**\n * @internal\n */\nfunction notificationResultAndContext(value: Struct) {\n return pick({\n context: pick({\n slot: number(),\n }),\n value,\n });\n}\n\n/**\n * @internal\n */\nfunction versionedMessageFromResponse(\n version: TransactionVersion | undefined,\n response: MessageResponse,\n): VersionedMessage {\n if (version === 0) {\n return new MessageV0({\n header: response.header,\n staticAccountKeys: response.accountKeys.map(\n accountKey => new PublicKey(accountKey),\n ),\n recentBlockhash: response.recentBlockhash,\n compiledInstructions: response.instructions.map(ix => ({\n programIdIndex: ix.programIdIndex,\n accountKeyIndexes: ix.accounts,\n data: bs58.decode(ix.data),\n })),\n addressTableLookups: response.addressTableLookups!,\n });\n } else {\n return new Message(response);\n }\n}\n\n/**\n * The level of commitment desired when querying state\n *
\n *   'processed': Query the most recent block which has reached 1 confirmation by the connected node\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\nexport type Commitment =\n | 'processed'\n | 'confirmed'\n | 'finalized'\n | 'recent' // Deprecated as of v1.5.5\n | 'single' // Deprecated as of v1.5.5\n | 'singleGossip' // Deprecated as of v1.5.5\n | 'root' // Deprecated as of v1.5.5\n | 'max'; // Deprecated as of v1.5.5\n\n/**\n * A subset of Commitment levels, which are at least optimistically confirmed\n *
\n *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster\n *   'finalized': Query the most recent block which has been finalized by the cluster\n * 
\n */\nexport type Finality = 'confirmed' | 'finalized';\n\n/**\n * Filter for largest accounts query\n *
\n *   'circulating':    Return the largest accounts that are part of the circulating supply\n *   'nonCirculating': Return the largest accounts that are not part of the circulating supply\n * 
\n */\nexport type LargestAccountsFilter = 'circulating' | 'nonCirculating';\n\n/**\n * Configuration object for changing `getAccountInfo` query behavior\n */\nexport type GetAccountInfoConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n /** Optional data slice to limit the returned account data */\n dataSlice?: DataSlice;\n};\n\n/**\n * Configuration object for changing `getBalance` query behavior\n */\nexport type GetBalanceConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\nexport type GetBlockConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n /**\n * Whether to populate the rewards array. If parameter not provided, the default includes rewards.\n */\n rewards?: boolean;\n /**\n * Level of transaction detail to return, either \"full\", \"accounts\", \"signatures\", or \"none\". If\n * parameter not provided, the default detail level is \"full\". If \"accounts\" are requested,\n * transaction details only include signatures and an annotated list of accounts in each\n * transaction. Transaction metadata is limited to only: fee, err, pre_balances, post_balances,\n * pre_token_balances, and post_token_balances.\n */\n transactionDetails?: 'accounts' | 'full' | 'none' | 'signatures';\n};\n\n/**\n * Configuration object for changing `getBlock` query behavior\n */\nexport type GetVersionedBlockConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n /** The max transaction version to return in responses. If the requested transaction is a higher version, an error will be returned */\n maxSupportedTransactionVersion?: number;\n /**\n * Whether to populate the rewards array. If parameter not provided, the default includes rewards.\n */\n rewards?: boolean;\n /**\n * Level of transaction detail to return, either \"full\", \"accounts\", \"signatures\", or \"none\". If\n * parameter not provided, the default detail level is \"full\". If \"accounts\" are requested,\n * transaction details only include signatures and an annotated list of accounts in each\n * transaction. Transaction metadata is limited to only: fee, err, pre_balances, post_balances,\n * pre_token_balances, and post_token_balances.\n */\n transactionDetails?: 'accounts' | 'full' | 'none' | 'signatures';\n};\n\n/**\n * Configuration object for changing `getStakeMinimumDelegation` query behavior\n */\nexport type GetStakeMinimumDelegationConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n};\n\n/**\n * Configuration object for changing `getBlockHeight` query behavior\n */\nexport type GetBlockHeightConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getEpochInfo` query behavior\n */\nexport type GetEpochInfoConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getInflationReward` query behavior\n */\nexport type GetInflationRewardConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** An epoch for which the reward occurs. If omitted, the previous epoch will be used */\n epoch?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getLatestBlockhash` query behavior\n */\nexport type GetLatestBlockhashConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `isBlockhashValid` query behavior\n */\nexport type IsBlockhashValidConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getSlot` query behavior\n */\nexport type GetSlotConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getSlotLeader` query behavior\n */\nexport type GetSlotLeaderConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\nexport type GetTransactionConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n};\n\n/**\n * Configuration object for changing `getTransaction` query behavior\n */\nexport type GetVersionedTransactionConfig = {\n /** The level of finality desired */\n commitment?: Finality;\n /** The max transaction version to return in responses. If the requested transaction is a higher version, an error will be returned */\n maxSupportedTransactionVersion?: number;\n};\n\n/**\n * Configuration object for changing `getLargestAccounts` query behavior\n */\nexport type GetLargestAccountsConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** Filter largest accounts by whether they are part of the circulating supply */\n filter?: LargestAccountsFilter;\n};\n\n/**\n * Configuration object for changing `getSupply` request behavior\n */\nexport type GetSupplyConfig = {\n /** The level of commitment desired */\n commitment?: Commitment;\n /** Exclude non circulating accounts list from response */\n excludeNonCirculatingAccountsList?: boolean;\n};\n\n/**\n * Configuration object for changing query behavior\n */\nexport type SignatureStatusConfig = {\n /** enable searching status history, not needed for recent transactions */\n searchTransactionHistory: boolean;\n};\n\n/**\n * Information describing a cluster node\n */\nexport type ContactInfo = {\n /** Identity public key of the node */\n pubkey: string;\n /** Gossip network address for the node */\n gossip: string | null;\n /** TPU network address for the node (null if not available) */\n tpu: string | null;\n /** JSON RPC network address for the node (null if not available) */\n rpc: string | null;\n /** Software version of the node (null if not available) */\n version: string | null;\n};\n\n/**\n * Information describing a vote account\n */\nexport type VoteAccountInfo = {\n /** Public key of the vote account */\n votePubkey: string;\n /** Identity public key of the node voting with this account */\n nodePubkey: string;\n /** The stake, in lamports, delegated to this vote account and activated */\n activatedStake: number;\n /** Whether the vote account is staked for this epoch */\n epochVoteAccount: boolean;\n /** Recent epoch voting credit history for this voter */\n epochCredits: Array<[number, number, number]>;\n /** A percentage (0-100) of rewards payout owed to the voter */\n commission: number;\n /** Most recent slot voted on by this vote account */\n lastVote: number;\n};\n\n/**\n * A collection of cluster vote accounts\n */\nexport type VoteAccountStatus = {\n /** Active vote accounts */\n current: Array;\n /** Inactive vote accounts */\n delinquent: Array;\n};\n\n/**\n * Network Inflation\n * (see https://docs.solana.com/implemented-proposals/ed_overview)\n */\nexport type InflationGovernor = {\n foundation: number;\n foundationTerm: number;\n initial: number;\n taper: number;\n terminal: number;\n};\n\nconst GetInflationGovernorResult = pick({\n foundation: number(),\n foundationTerm: number(),\n initial: number(),\n taper: number(),\n terminal: number(),\n});\n\n/**\n * The inflation reward for an epoch\n */\nexport type InflationReward = {\n /** epoch for which the reward occurs */\n epoch: number;\n /** the slot in which the rewards are effective */\n effectiveSlot: number;\n /** reward amount in lamports */\n amount: number;\n /** post balance of the account in lamports */\n postBalance: number;\n /** vote account commission when the reward was credited */\n commission?: number | null;\n};\n\n/**\n * Expected JSON RPC response for the \"getInflationReward\" message\n */\nconst GetInflationRewardResult = jsonRpcResult(\n array(\n nullable(\n pick({\n epoch: number(),\n effectiveSlot: number(),\n amount: number(),\n postBalance: number(),\n commission: optional(nullable(number())),\n }),\n ),\n ),\n);\n\nexport type RecentPrioritizationFees = {\n /** slot in which the fee was observed */\n slot: number;\n /** the per-compute-unit fee paid by at least one successfully landed transaction, specified in increments of 0.000001 lamports*/\n prioritizationFee: number;\n};\n\n/**\n * Configuration object for changing `getRecentPrioritizationFees` query behavior\n */\nexport type GetRecentPrioritizationFeesConfig = {\n /**\n * If this parameter is provided, the response will reflect a fee to land a transaction locking\n * all of the provided accounts as writable.\n */\n lockedWritableAccounts?: PublicKey[];\n};\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesResult = array(\n pick({\n slot: number(),\n prioritizationFee: number(),\n }),\n);\n\nexport type InflationRate = {\n /** total inflation */\n total: number;\n /** inflation allocated to validators */\n validator: number;\n /** inflation allocated to the foundation */\n foundation: number;\n /** epoch for which these values are valid */\n epoch: number;\n};\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateResult = pick({\n total: number(),\n validator: number(),\n foundation: number(),\n epoch: number(),\n});\n\n/**\n * Information about the current epoch\n */\nexport type EpochInfo = {\n epoch: number;\n slotIndex: number;\n slotsInEpoch: number;\n absoluteSlot: number;\n blockHeight?: number;\n transactionCount?: number;\n};\n\nconst GetEpochInfoResult = pick({\n epoch: number(),\n slotIndex: number(),\n slotsInEpoch: number(),\n absoluteSlot: number(),\n blockHeight: optional(number()),\n transactionCount: optional(number()),\n});\n\nconst GetEpochScheduleResult = pick({\n slotsPerEpoch: number(),\n leaderScheduleSlotOffset: number(),\n warmup: boolean(),\n firstNormalEpoch: number(),\n firstNormalSlot: number(),\n});\n\n/**\n * Leader schedule\n * (see https://docs.solana.com/terminology#leader-schedule)\n */\nexport type LeaderSchedule = {\n [address: string]: number[];\n};\n\nconst GetLeaderScheduleResult = record(string(), array(number()));\n\n/**\n * Transaction error or null\n */\nconst TransactionErrorResult = nullable(union([pick({}), string()]));\n\n/**\n * Signature status for a transaction\n */\nconst SignatureStatusResult = pick({\n err: TransactionErrorResult,\n});\n\n/**\n * Transaction signature received notification\n */\nconst SignatureReceivedResult = literal('receivedSignature');\n\n/**\n * Version info for a node\n */\nexport type Version = {\n /** Version of solana-core */\n 'solana-core': string;\n 'feature-set'?: number;\n};\n\nconst VersionResult = pick({\n 'solana-core': string(),\n 'feature-set': optional(number()),\n});\n\nexport type SimulatedTransactionAccountInfo = {\n /** `true` if this account's data contains a loaded program */\n executable: boolean;\n /** Identifier of the program that owns the account */\n owner: string;\n /** Number of lamports assigned to the account */\n lamports: number;\n /** Optional data assigned to the account */\n data: string[];\n /** Optional rent epoch info for account */\n rentEpoch?: number;\n};\n\nexport type TransactionReturnDataEncoding = 'base64';\n\nexport type TransactionReturnData = {\n programId: string;\n data: [string, TransactionReturnDataEncoding];\n};\n\nexport type SimulateTransactionConfig = {\n /** Optional parameter used to enable signature verification before simulation */\n sigVerify?: boolean;\n /** Optional parameter used to replace the simulated transaction's recent blockhash with the latest blockhash */\n replaceRecentBlockhash?: boolean;\n /** Optional parameter used to set the commitment level when selecting the latest block */\n commitment?: Commitment;\n /** Optional parameter used to specify a list of base58-encoded account addresses to return post simulation state for */\n accounts?: {\n /** The encoding of the returned account's data */\n encoding: 'base64';\n addresses: string[];\n };\n /** Optional parameter used to specify the minimum block slot that can be used for simulation */\n minContextSlot?: number;\n /** Optional parameter used to include inner instructions in the simulation */\n innerInstructions?: boolean;\n};\n\nexport type SimulatedTransactionResponse = {\n err: TransactionError | string | null;\n logs: Array | null;\n accounts?: (SimulatedTransactionAccountInfo | null)[] | null;\n unitsConsumed?: number;\n returnData?: TransactionReturnData | null;\n innerInstructions?: ParsedInnerInstruction[] | null;\n};\nconst ParsedInstructionStruct = pick({\n program: string(),\n programId: PublicKeyFromString,\n parsed: unknown(),\n});\n\nconst PartiallyDecodedInstructionStruct = pick({\n programId: PublicKeyFromString,\n accounts: array(PublicKeyFromString),\n data: string(),\n});\n\nconst SimulatedTransactionResponseStruct = jsonRpcResultAndContext(\n pick({\n err: nullable(union([pick({}), string()])),\n logs: nullable(array(string())),\n accounts: optional(\n nullable(\n array(\n nullable(\n pick({\n executable: boolean(),\n owner: string(),\n lamports: number(),\n data: array(string()),\n rentEpoch: optional(number()),\n }),\n ),\n ),\n ),\n ),\n unitsConsumed: optional(number()),\n returnData: optional(\n nullable(\n pick({\n programId: string(),\n data: tuple([string(), literal('base64')]),\n }),\n ),\n ),\n innerInstructions: optional(\n nullable(\n array(\n pick({\n index: number(),\n instructions: array(\n union([\n ParsedInstructionStruct,\n PartiallyDecodedInstructionStruct,\n ]),\n ),\n }),\n ),\n ),\n ),\n }),\n);\n\nexport type ParsedInnerInstruction = {\n index: number;\n instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];\n};\n\nexport type TokenBalance = {\n accountIndex: number;\n mint: string;\n owner?: string;\n uiTokenAmount: TokenAmount;\n};\n\n/**\n * Metadata for a parsed confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link ParsedTransactionMeta} instead.\n */\nexport type ParsedConfirmedTransactionMeta = ParsedTransactionMeta;\n\n/**\n * Collection of addresses loaded by a transaction using address table lookups\n */\nexport type LoadedAddresses = {\n writable: Array;\n readonly: Array;\n};\n\n/**\n * Metadata for a parsed transaction on the ledger\n */\nexport type ParsedTransactionMeta = {\n /** The fee charged for processing the transaction */\n fee: number;\n /** An array of cross program invoked parsed instructions */\n innerInstructions?: ParsedInnerInstruction[] | null;\n /** The balances of the transaction accounts before processing */\n preBalances: Array;\n /** The balances of the transaction accounts after processing */\n postBalances: Array;\n /** An array of program log messages emitted during a transaction */\n logMessages?: Array | null;\n /** The token balances of the transaction accounts before processing */\n preTokenBalances?: Array | null;\n /** The token balances of the transaction accounts after processing */\n postTokenBalances?: Array | null;\n /** The error result of transaction processing */\n err: TransactionError | null;\n /** The collection of addresses loaded using address lookup tables */\n loadedAddresses?: LoadedAddresses;\n /** The compute units consumed after processing the transaction */\n computeUnitsConsumed?: number;\n};\n\nexport type CompiledInnerInstruction = {\n index: number;\n instructions: CompiledInstruction[];\n};\n\n/**\n * Metadata for a confirmed transaction on the ledger\n */\nexport type ConfirmedTransactionMeta = {\n /** The fee charged for processing the transaction */\n fee: number;\n /** An array of cross program invoked instructions */\n innerInstructions?: CompiledInnerInstruction[] | null;\n /** The balances of the transaction accounts before processing */\n preBalances: Array;\n /** The balances of the transaction accounts after processing */\n postBalances: Array;\n /** An array of program log messages emitted during a transaction */\n logMessages?: Array | null;\n /** The token balances of the transaction accounts before processing */\n preTokenBalances?: Array | null;\n /** The token balances of the transaction accounts after processing */\n postTokenBalances?: Array | null;\n /** The error result of transaction processing */\n err: TransactionError | null;\n /** The collection of addresses loaded using address lookup tables */\n loadedAddresses?: LoadedAddresses;\n /** The compute units consumed after processing the transaction */\n computeUnitsConsumed?: number;\n};\n\n/**\n * A processed transaction from the RPC API\n */\nexport type TransactionResponse = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: Message;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n};\n\n/**\n * A processed transaction from the RPC API\n */\nexport type VersionedTransactionResponse = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: VersionedMessage;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n /** The transaction version */\n version?: TransactionVersion;\n};\n\n/**\n * A processed transaction message from the RPC API\n */\ntype MessageResponse = {\n accountKeys: string[];\n header: MessageHeader;\n instructions: CompiledInstruction[];\n recentBlockhash: string;\n addressTableLookups?: ParsedAddressTableLookup[];\n};\n\n/**\n * A confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0.\n */\nexport type ConfirmedTransaction = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The details of the transaction */\n transaction: Transaction;\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n};\n\n/**\n * A partially decoded transaction instruction\n */\nexport type PartiallyDecodedInstruction = {\n /** Program id called by this instruction */\n programId: PublicKey;\n /** Public keys of accounts passed to this instruction */\n accounts: Array;\n /** Raw base-58 instruction data */\n data: string;\n};\n\n/**\n * A parsed transaction message account\n */\nexport type ParsedMessageAccount = {\n /** Public key of the account */\n pubkey: PublicKey;\n /** Indicates if the account signed the transaction */\n signer: boolean;\n /** Indicates if the account is writable for this transaction */\n writable: boolean;\n /** Indicates if the account key came from the transaction or a lookup table */\n source?: 'transaction' | 'lookupTable';\n};\n\n/**\n * A parsed transaction instruction\n */\nexport type ParsedInstruction = {\n /** Name of the program for this instruction */\n program: string;\n /** ID of the program for this instruction */\n programId: PublicKey;\n /** Parsed instruction info */\n parsed: any;\n};\n\n/**\n * A parsed address table lookup\n */\nexport type ParsedAddressTableLookup = {\n /** Address lookup table account key */\n accountKey: PublicKey;\n /** Parsed instruction info */\n writableIndexes: number[];\n /** Parsed instruction info */\n readonlyIndexes: number[];\n};\n\n/**\n * A parsed transaction message\n */\nexport type ParsedMessage = {\n /** Accounts used in the instructions */\n accountKeys: ParsedMessageAccount[];\n /** The atomically executed instructions for the transaction */\n instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];\n /** Recent blockhash */\n recentBlockhash: string;\n /** Address table lookups used to load additional accounts */\n addressTableLookups?: ParsedAddressTableLookup[] | null;\n};\n\n/**\n * A parsed transaction\n */\nexport type ParsedTransaction = {\n /** Signatures for the transaction */\n signatures: Array;\n /** Message of the transaction */\n message: ParsedMessage;\n};\n\n/**\n * A parsed and confirmed transaction on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link ParsedTransactionWithMeta} instead.\n */\nexport type ParsedConfirmedTransaction = ParsedTransactionWithMeta;\n\n/**\n * A parsed transaction on the ledger with meta\n */\nexport type ParsedTransactionWithMeta = {\n /** The slot during which the transaction was processed */\n slot: number;\n /** The details of the transaction */\n transaction: ParsedTransaction;\n /** Metadata produced from the transaction */\n meta: ParsedTransactionMeta | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n /** The version of the transaction message */\n version?: TransactionVersion;\n};\n\n/**\n * A processed block fetched from the RPC API\n */\nexport type BlockResponse = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions with status meta and original message */\n transactions: Array<{\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: Message;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The transaction version */\n version?: TransactionVersion;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n /** Public key of reward recipient */\n pubkey: string;\n /** Reward value in lamports */\n lamports: number;\n /** Account balance after reward is applied */\n postBalance: number | null;\n /** Type of reward received */\n rewardType: string | null;\n /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\nexport type AccountsModeBlockResponse = VersionedAccountsModeBlockResponse;\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\nexport type NoneModeBlockResponse = VersionedNoneModeBlockResponse;\n\n/**\n * A block with parsed transactions\n */\nexport type ParsedBlockResponse = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions with status meta and original message */\n transactions: Array<{\n /** The details of the transaction */\n transaction: ParsedTransaction;\n /** Metadata produced from the transaction */\n meta: ParsedTransactionMeta | null;\n /** The transaction version */\n version?: TransactionVersion;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n /** Public key of reward recipient */\n pubkey: string;\n /** Reward value in lamports */\n lamports: number;\n /** Account balance after reward is applied */\n postBalance: number | null;\n /** Type of reward received */\n rewardType: string | null;\n /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n /** The number of blocks beneath this block */\n blockHeight: number | null;\n};\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `accounts`\n */\nexport type ParsedAccountsModeBlockResponse = Omit<\n ParsedBlockResponse,\n 'transactions'\n> & {\n transactions: Array<\n Omit & {\n transaction: Pick<\n ParsedBlockResponse['transactions'][number]['transaction'],\n 'signatures'\n > & {\n accountKeys: ParsedMessageAccount[];\n };\n }\n >;\n};\n\n/**\n * A block with parsed transactions where the `transactionDetails` mode is `none`\n */\nexport type ParsedNoneModeBlockResponse = Omit<\n ParsedBlockResponse,\n 'transactions'\n>;\n\n/**\n * A processed block fetched from the RPC API\n */\nexport type VersionedBlockResponse = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions with status meta and original message */\n transactions: Array<{\n /** The transaction */\n transaction: {\n /** The transaction message */\n message: VersionedMessage;\n /** The transaction signatures */\n signatures: string[];\n };\n /** Metadata produced from the transaction */\n meta: ConfirmedTransactionMeta | null;\n /** The transaction version */\n version?: TransactionVersion;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n /** Public key of reward recipient */\n pubkey: string;\n /** Reward value in lamports */\n lamports: number;\n /** Account balance after reward is applied */\n postBalance: number | null;\n /** Type of reward received */\n rewardType: string | null;\n /** Vote account commission when the reward was credited, only present for voting and staking rewards */\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `accounts`\n */\nexport type VersionedAccountsModeBlockResponse = Omit<\n VersionedBlockResponse,\n 'transactions'\n> & {\n transactions: Array<\n Omit & {\n transaction: Pick<\n VersionedBlockResponse['transactions'][number]['transaction'],\n 'signatures'\n > & {\n accountKeys: ParsedMessageAccount[];\n };\n }\n >;\n};\n\n/**\n * A processed block fetched from the RPC API where the `transactionDetails` mode is `none`\n */\nexport type VersionedNoneModeBlockResponse = Omit<\n VersionedBlockResponse,\n 'transactions'\n>;\n\n/**\n * A confirmed block on the ledger\n *\n * @deprecated Deprecated since RPC v1.8.0.\n */\nexport type ConfirmedBlock = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of transactions and status metas */\n transactions: Array<{\n transaction: Transaction;\n meta: ConfirmedTransactionMeta | null;\n }>;\n /** Vector of block rewards */\n rewards?: Array<{\n pubkey: string;\n lamports: number;\n postBalance: number | null;\n rewardType: string | null;\n commission?: number | null;\n }>;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * A Block on the ledger with signatures only\n */\nexport type BlockSignatures = {\n /** Blockhash of this block */\n blockhash: Blockhash;\n /** Blockhash of this block's parent */\n previousBlockhash: Blockhash;\n /** Slot index of this block's parent */\n parentSlot: number;\n /** Vector of signatures */\n signatures: Array;\n /** The unix timestamp of when the block was processed */\n blockTime: number | null;\n};\n\n/**\n * recent block production information\n */\nexport type BlockProduction = Readonly<{\n /** a dictionary of validator identities, as base-58 encoded strings. Value is a two element array containing the number of leader slots and the number of blocks produced */\n byIdentity: Readonly>>;\n /** Block production slot range */\n range: Readonly<{\n /** first slot of the block production information (inclusive) */\n firstSlot: number;\n /** last slot of block production information (inclusive) */\n lastSlot: number;\n }>;\n}>;\n\nexport type GetBlockProductionConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Slot range to return block production for. If parameter not provided, defaults to current epoch. */\n range?: {\n /** first slot to return block production information for (inclusive) */\n firstSlot: number;\n /** last slot to return block production information for (inclusive). If parameter not provided, defaults to the highest slot */\n lastSlot?: number;\n };\n /** Only return results for this validator identity (base-58 encoded) */\n identity?: string;\n};\n\n/**\n * Expected JSON RPC response for the \"getBlockProduction\" message\n */\nconst BlockProductionResponseStruct = jsonRpcResultAndContext(\n pick({\n byIdentity: record(string(), array(number())),\n range: pick({\n firstSlot: number(),\n lastSlot: number(),\n }),\n }),\n);\n\n/**\n * A performance sample\n */\nexport type PerfSample = {\n /** Slot number of sample */\n slot: number;\n /** Number of transactions in a sample window */\n numTransactions: number;\n /** Number of slots in a sample window */\n numSlots: number;\n /** Sample window in seconds */\n samplePeriodSecs: number;\n};\n\nfunction createRpcClient(\n url: string,\n httpHeaders?: HttpHeaders,\n customFetch?: FetchFn,\n fetchMiddleware?: FetchMiddleware,\n disableRetryOnRateLimit?: boolean,\n httpAgent?: NodeHttpAgent | NodeHttpsAgent | false,\n): RpcClient {\n const fetch = customFetch ? customFetch : fetchImpl;\n let agent: NodeHttpAgent | NodeHttpsAgent | undefined;\n if (process.env.BROWSER) {\n if (httpAgent != null) {\n console.warn(\n 'You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' +\n 'It has been ignored; `httpAgent` is only used in Node environments.',\n );\n }\n } else {\n if (httpAgent == null) {\n if (process.env.NODE_ENV !== 'test') {\n const agentOptions = {\n // One second fewer than the Solana RPC's keepalive timeout.\n // Read more: https://github.com/solana-labs/solana/issues/27859#issuecomment-1340097889\n freeSocketTimeout: 19000,\n keepAlive: true,\n maxSockets: 25,\n };\n if (url.startsWith('https:')) {\n agent = new HttpsKeepAliveAgent(agentOptions);\n } else {\n agent = new HttpKeepAliveAgent(agentOptions);\n }\n }\n } else {\n if (httpAgent !== false) {\n const isHttps = url.startsWith('https:');\n if (isHttps && !(httpAgent instanceof NodeHttpsAgent)) {\n throw new Error(\n 'The endpoint `' +\n url +\n '` can only be paired with an `https.Agent`. You have, instead, supplied an ' +\n '`http.Agent` through `httpAgent`.',\n );\n } else if (!isHttps && httpAgent instanceof NodeHttpsAgent) {\n throw new Error(\n 'The endpoint `' +\n url +\n '` can only be paired with an `http.Agent`. You have, instead, supplied an ' +\n '`https.Agent` through `httpAgent`.',\n );\n }\n agent = httpAgent;\n }\n }\n }\n\n let fetchWithMiddleware: FetchFn | undefined;\n\n if (fetchMiddleware) {\n fetchWithMiddleware = async (info, init) => {\n const modifiedFetchArgs = await new Promise>(\n (resolve, reject) => {\n try {\n fetchMiddleware(info, init, (modifiedInfo, modifiedInit) =>\n resolve([modifiedInfo, modifiedInit]),\n );\n } catch (error) {\n reject(error);\n }\n },\n );\n return await fetch(...modifiedFetchArgs);\n };\n }\n\n const clientBrowser = new RpcClient(async (request, callback) => {\n const options = {\n method: 'POST',\n body: request,\n agent,\n headers: Object.assign(\n {\n 'Content-Type': 'application/json',\n },\n httpHeaders || {},\n COMMON_HTTP_HEADERS,\n ),\n };\n\n try {\n let too_many_requests_retries = 5;\n let res: Response;\n let waitTime = 500;\n for (;;) {\n if (fetchWithMiddleware) {\n res = await fetchWithMiddleware(url, options);\n } else {\n res = await fetch(url, options);\n }\n\n if (res.status !== 429 /* Too many requests */) {\n break;\n }\n if (disableRetryOnRateLimit === true) {\n break;\n }\n too_many_requests_retries -= 1;\n if (too_many_requests_retries === 0) {\n break;\n }\n console.error(\n `Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`,\n );\n await sleep(waitTime);\n waitTime *= 2;\n }\n\n const text = await res.text();\n if (res.ok) {\n callback(null, text);\n } else {\n callback(new Error(`${res.status} ${res.statusText}: ${text}`));\n }\n } catch (err) {\n if (err instanceof Error) callback(err);\n }\n }, {});\n\n return clientBrowser;\n}\n\nfunction createRpcRequest(client: RpcClient): RpcRequest {\n return (method, args) => {\n return new Promise((resolve, reject) => {\n client.request(method, args, (err: any, response: any) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\n\nfunction createRpcBatchRequest(client: RpcClient): RpcBatchRequest {\n return (requests: RpcParams[]) => {\n return new Promise((resolve, reject) => {\n // Do nothing if requests is empty\n if (requests.length === 0) resolve([]);\n\n const batch = requests.map((params: RpcParams) => {\n return client.request(params.methodName, params.args);\n });\n\n client.request(batch, (err: any, response: any) => {\n if (err) {\n reject(err);\n return;\n }\n resolve(response);\n });\n });\n };\n}\n\n/**\n * Expected JSON RPC response for the \"getInflationGovernor\" message\n */\nconst GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult);\n\n/**\n * Expected JSON RPC response for the \"getInflationRate\" message\n */\nconst GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult);\n\n/**\n * Expected JSON RPC response for the \"getRecentPrioritizationFees\" message\n */\nconst GetRecentPrioritizationFeesRpcResult = jsonRpcResult(\n GetRecentPrioritizationFeesResult,\n);\n\n/**\n * Expected JSON RPC response for the \"getEpochInfo\" message\n */\nconst GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult);\n\n/**\n * Expected JSON RPC response for the \"getEpochSchedule\" message\n */\nconst GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"getLeaderSchedule\" message\n */\nconst GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult);\n\n/**\n * Expected JSON RPC response for the \"minimumLedgerSlot\" and \"getFirstAvailableBlock\" messages\n */\nconst SlotRpcResult = jsonRpcResult(number());\n\n/**\n * Supply\n */\nexport type Supply = {\n /** Total supply in lamports */\n total: number;\n /** Circulating supply in lamports */\n circulating: number;\n /** Non-circulating supply in lamports */\n nonCirculating: number;\n /** List of non-circulating account addresses */\n nonCirculatingAccounts: Array;\n};\n\n/**\n * Expected JSON RPC response for the \"getSupply\" message\n */\nconst GetSupplyRpcResult = jsonRpcResultAndContext(\n pick({\n total: number(),\n circulating: number(),\n nonCirculating: number(),\n nonCirculatingAccounts: array(PublicKeyFromString),\n }),\n);\n\n/**\n * Token amount object which returns a token amount in different formats\n * for various client use cases.\n */\nexport type TokenAmount = {\n /** Raw amount of tokens as string ignoring decimals */\n amount: string;\n /** Number of decimals configured for token's mint */\n decimals: number;\n /** Token amount as float, accounts for decimals */\n uiAmount: number | null;\n /** Token amount as string, accounts for decimals */\n uiAmountString?: string;\n};\n\n/**\n * Expected JSON RPC structure for token amounts\n */\nconst TokenAmountResult = pick({\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string()),\n});\n\n/**\n * Token address and balance.\n */\nexport type TokenAccountBalancePair = {\n /** Address of the token account */\n address: PublicKey;\n /** Raw amount of tokens as string ignoring decimals */\n amount: string;\n /** Number of decimals configured for token's mint */\n decimals: number;\n /** Token amount as float, accounts for decimals */\n uiAmount: number | null;\n /** Token amount as string, accounts for decimals */\n uiAmountString?: string;\n};\n\n/**\n * Expected JSON RPC response for the \"getTokenLargestAccounts\" message\n */\nconst GetTokenLargestAccountsResult = jsonRpcResultAndContext(\n array(\n pick({\n address: PublicKeyFromString,\n amount: string(),\n uiAmount: nullable(number()),\n decimals: number(),\n uiAmountString: optional(string()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message\n */\nconst GetTokenAccountsByOwner = jsonRpcResultAndContext(\n array(\n pick({\n pubkey: PublicKeyFromString,\n account: pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number(),\n }),\n }),\n ),\n);\n\nconst ParsedAccountDataResult = pick({\n program: string(),\n parsed: unknown(),\n space: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"getTokenAccountsByOwner\" message with parsed data\n */\nconst GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(\n array(\n pick({\n pubkey: PublicKeyFromString,\n account: pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedAccountDataResult,\n rentEpoch: number(),\n }),\n }),\n ),\n);\n\n/**\n * Pair of an account address and its balance\n */\nexport type AccountBalancePair = {\n address: PublicKey;\n lamports: number;\n};\n\n/**\n * Expected JSON RPC response for the \"getLargestAccounts\" message\n */\nconst GetLargestAccountsRpcResult = jsonRpcResultAndContext(\n array(\n pick({\n lamports: number(),\n address: PublicKeyFromString,\n }),\n ),\n);\n\n/**\n * @internal\n */\nconst AccountInfoResult = pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: BufferFromRawAccountData,\n rentEpoch: number(),\n});\n\n/**\n * @internal\n */\nconst KeyedAccountInfoResult = pick({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult,\n});\n\nconst ParsedOrRawAccountData = coerce(\n union([instance(Buffer), ParsedAccountDataResult]),\n union([RawAccountDataResult, ParsedAccountDataResult]),\n value => {\n if (Array.isArray(value)) {\n return create(value, BufferFromRawAccountData);\n } else {\n return value;\n }\n },\n);\n\n/**\n * @internal\n */\nconst ParsedAccountInfoResult = pick({\n executable: boolean(),\n owner: PublicKeyFromString,\n lamports: number(),\n data: ParsedOrRawAccountData,\n rentEpoch: number(),\n});\n\nconst KeyedParsedAccountInfoResult = pick({\n pubkey: PublicKeyFromString,\n account: ParsedAccountInfoResult,\n});\n\n/**\n * @internal\n */\nconst StakeActivationResult = pick({\n state: union([\n literal('active'),\n literal('inactive'),\n literal('activating'),\n literal('deactivating'),\n ]),\n active: number(),\n inactive: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"getConfirmedSignaturesForAddress2\" message\n */\n\nconst GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(\n array(\n pick({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number())),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getSignaturesForAddress\" message\n */\nconst GetSignaturesForAddressRpcResult = jsonRpcResult(\n array(\n pick({\n signature: string(),\n slot: number(),\n err: TransactionErrorResult,\n memo: nullable(string()),\n blockTime: optional(nullable(number())),\n }),\n ),\n);\n\n/***\n * Expected JSON RPC response for the \"accountNotification\" message\n */\nconst AccountNotificationResult = pick({\n subscription: number(),\n result: notificationResultAndContext(AccountInfoResult),\n});\n\n/**\n * @internal\n */\nconst ProgramAccountInfoResult = pick({\n pubkey: PublicKeyFromString,\n account: AccountInfoResult,\n});\n\n/***\n * Expected JSON RPC response for the \"programNotification\" message\n */\nconst ProgramAccountNotificationResult = pick({\n subscription: number(),\n result: notificationResultAndContext(ProgramAccountInfoResult),\n});\n\n/**\n * @internal\n */\nconst SlotInfoResult = pick({\n parent: number(),\n slot: number(),\n root: number(),\n});\n\n/**\n * Expected JSON RPC response for the \"slotNotification\" message\n */\nconst SlotNotificationResult = pick({\n subscription: number(),\n result: SlotInfoResult,\n});\n\n/**\n * Slot updates which can be used for tracking the live progress of a cluster.\n * - `\"firstShredReceived\"`: connected node received the first shred of a block.\n * Indicates that a new block that is being produced.\n * - `\"completed\"`: connected node has received all shreds of a block. Indicates\n * a block was recently produced.\n * - `\"optimisticConfirmation\"`: block was optimistically confirmed by the\n * cluster. It is not guaranteed that an optimistic confirmation notification\n * will be sent for every finalized blocks.\n * - `\"root\"`: the connected node rooted this block.\n * - `\"createdBank\"`: the connected node has started validating this block.\n * - `\"frozen\"`: the connected node has validated this block.\n * - `\"dead\"`: the connected node failed to validate this block.\n */\nexport type SlotUpdate =\n | {\n type: 'firstShredReceived';\n slot: number;\n timestamp: number;\n }\n | {\n type: 'completed';\n slot: number;\n timestamp: number;\n }\n | {\n type: 'createdBank';\n slot: number;\n timestamp: number;\n parent: number;\n }\n | {\n type: 'frozen';\n slot: number;\n timestamp: number;\n stats: {\n numTransactionEntries: number;\n numSuccessfulTransactions: number;\n numFailedTransactions: number;\n maxTransactionsPerEntry: number;\n };\n }\n | {\n type: 'dead';\n slot: number;\n timestamp: number;\n err: string;\n }\n | {\n type: 'optimisticConfirmation';\n slot: number;\n timestamp: number;\n }\n | {\n type: 'root';\n slot: number;\n timestamp: number;\n };\n\n/**\n * @internal\n */\nconst SlotUpdateResult = union([\n pick({\n type: union([\n literal('firstShredReceived'),\n literal('completed'),\n literal('optimisticConfirmation'),\n literal('root'),\n ]),\n slot: number(),\n timestamp: number(),\n }),\n pick({\n type: literal('createdBank'),\n parent: number(),\n slot: number(),\n timestamp: number(),\n }),\n pick({\n type: literal('frozen'),\n slot: number(),\n timestamp: number(),\n stats: pick({\n numTransactionEntries: number(),\n numSuccessfulTransactions: number(),\n numFailedTransactions: number(),\n maxTransactionsPerEntry: number(),\n }),\n }),\n pick({\n type: literal('dead'),\n slot: number(),\n timestamp: number(),\n err: string(),\n }),\n]);\n\n/**\n * Expected JSON RPC response for the \"slotsUpdatesNotification\" message\n */\nconst SlotUpdateNotificationResult = pick({\n subscription: number(),\n result: SlotUpdateResult,\n});\n\n/**\n * Expected JSON RPC response for the \"signatureNotification\" message\n */\nconst SignatureNotificationResult = pick({\n subscription: number(),\n result: notificationResultAndContext(\n union([SignatureStatusResult, SignatureReceivedResult]),\n ),\n});\n\n/**\n * Expected JSON RPC response for the \"rootNotification\" message\n */\nconst RootNotificationResult = pick({\n subscription: number(),\n result: number(),\n});\n\nconst ContactInfoResult = pick({\n pubkey: string(),\n gossip: nullable(string()),\n tpu: nullable(string()),\n rpc: nullable(string()),\n version: nullable(string()),\n});\n\nconst VoteAccountInfoResult = pick({\n votePubkey: string(),\n nodePubkey: string(),\n activatedStake: number(),\n epochVoteAccount: boolean(),\n epochCredits: array(tuple([number(), number(), number()])),\n commission: number(),\n lastVote: number(),\n rootSlot: nullable(number()),\n});\n\n/**\n * Expected JSON RPC response for the \"getVoteAccounts\" message\n */\nconst GetVoteAccounts = jsonRpcResult(\n pick({\n current: array(VoteAccountInfoResult),\n delinquent: array(VoteAccountInfoResult),\n }),\n);\n\nconst ConfirmationStatus = union([\n literal('processed'),\n literal('confirmed'),\n literal('finalized'),\n]);\n\nconst SignatureStatusResponse = pick({\n slot: number(),\n confirmations: nullable(number()),\n err: TransactionErrorResult,\n confirmationStatus: optional(ConfirmationStatus),\n});\n\n/**\n * Expected JSON RPC response for the \"getSignatureStatuses\" message\n */\nconst GetSignatureStatusesRpcResult = jsonRpcResultAndContext(\n array(nullable(SignatureStatusResponse)),\n);\n\n/**\n * Expected JSON RPC response for the \"getMinimumBalanceForRentExemption\" message\n */\nconst GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number());\n\nconst AddressTableLookupStruct = pick({\n accountKey: PublicKeyFromString,\n writableIndexes: array(number()),\n readonlyIndexes: array(number()),\n});\n\nconst ConfirmedTransactionResult = pick({\n signatures: array(string()),\n message: pick({\n accountKeys: array(string()),\n header: pick({\n numRequiredSignatures: number(),\n numReadonlySignedAccounts: number(),\n numReadonlyUnsignedAccounts: number(),\n }),\n instructions: array(\n pick({\n accounts: array(number()),\n data: string(),\n programIdIndex: number(),\n }),\n ),\n recentBlockhash: string(),\n addressTableLookups: optional(array(AddressTableLookupStruct)),\n }),\n});\n\nconst AnnotatedAccountKey = pick({\n pubkey: PublicKeyFromString,\n signer: boolean(),\n writable: boolean(),\n source: optional(union([literal('transaction'), literal('lookupTable')])),\n});\n\nconst ConfirmedTransactionAccountsModeResult = pick({\n accountKeys: array(AnnotatedAccountKey),\n signatures: array(string()),\n});\n\nconst ParsedInstructionResult = pick({\n parsed: unknown(),\n program: string(),\n programId: PublicKeyFromString,\n});\n\nconst RawInstructionResult = pick({\n accounts: array(PublicKeyFromString),\n data: string(),\n programId: PublicKeyFromString,\n});\n\nconst InstructionResult = union([\n RawInstructionResult,\n ParsedInstructionResult,\n]);\n\nconst UnknownInstructionResult = union([\n pick({\n parsed: unknown(),\n program: string(),\n programId: string(),\n }),\n pick({\n accounts: array(string()),\n data: string(),\n programId: string(),\n }),\n]);\n\nconst ParsedOrRawInstruction = coerce(\n InstructionResult,\n UnknownInstructionResult,\n value => {\n if ('accounts' in value) {\n return create(value, RawInstructionResult);\n } else {\n return create(value, ParsedInstructionResult);\n }\n },\n);\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionResult = pick({\n signatures: array(string()),\n message: pick({\n accountKeys: array(AnnotatedAccountKey),\n instructions: array(ParsedOrRawInstruction),\n recentBlockhash: string(),\n addressTableLookups: optional(nullable(array(AddressTableLookupStruct))),\n }),\n});\n\nconst TokenBalanceResult = pick({\n accountIndex: number(),\n mint: string(),\n owner: optional(string()),\n uiTokenAmount: TokenAmountResult,\n});\n\nconst LoadedAddressesResult = pick({\n writable: array(PublicKeyFromString),\n readonly: array(PublicKeyFromString),\n});\n\n/**\n * @internal\n */\nconst ConfirmedTransactionMetaResult = pick({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(\n nullable(\n array(\n pick({\n index: number(),\n instructions: array(\n pick({\n accounts: array(number()),\n data: string(),\n programIdIndex: number(),\n }),\n ),\n }),\n ),\n ),\n ),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n});\n\n/**\n * @internal\n */\nconst ParsedConfirmedTransactionMetaResult = pick({\n err: TransactionErrorResult,\n fee: number(),\n innerInstructions: optional(\n nullable(\n array(\n pick({\n index: number(),\n instructions: array(ParsedOrRawInstruction),\n }),\n ),\n ),\n ),\n preBalances: array(number()),\n postBalances: array(number()),\n logMessages: optional(nullable(array(string()))),\n preTokenBalances: optional(nullable(array(TokenBalanceResult))),\n postTokenBalances: optional(nullable(array(TokenBalanceResult))),\n loadedAddresses: optional(LoadedAddressesResult),\n computeUnitsConsumed: optional(number()),\n});\n\nconst TransactionVersionStruct = union([literal(0), literal('legacy')]);\n\n/** @internal */\nconst RewardsResult = pick({\n pubkey: string(),\n lamports: number(),\n postBalance: nullable(number()),\n rewardType: nullable(string()),\n commission: optional(nullable(number())),\n});\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetNoneModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetAccountsModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message\n */\nconst GetParsedBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `accounts`\n */\nconst GetParsedAccountsModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionAccountsModeResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n version: optional(TransactionVersionStruct),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getBlock\" message when `transactionDetails` is `none`\n */\nconst GetParsedNoneModeBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n blockHeight: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getConfirmedBlock\" message\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link GetBlockRpcResult} instead.\n */\nconst GetConfirmedBlockRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n transactions: array(\n pick({\n transaction: ConfirmedTransactionResult,\n meta: nullable(ConfirmedTransactionMetaResult),\n }),\n ),\n rewards: optional(array(RewardsResult)),\n blockTime: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getBlock\" message\n */\nconst GetBlockSignaturesRpcResult = jsonRpcResult(\n nullable(\n pick({\n blockhash: string(),\n previousBlockhash: string(),\n parentSlot: number(),\n signatures: array(string()),\n blockTime: nullable(number()),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getTransaction\" message\n */\nconst GetTransactionRpcResult = jsonRpcResult(\n nullable(\n pick({\n slot: number(),\n meta: nullable(ConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n transaction: ConfirmedTransactionResult,\n version: optional(TransactionVersionStruct),\n }),\n ),\n);\n\n/**\n * Expected parsed JSON RPC response for the \"getTransaction\" message\n */\nconst GetParsedTransactionRpcResult = jsonRpcResult(\n nullable(\n pick({\n slot: number(),\n transaction: ParsedConfirmedTransactionResult,\n meta: nullable(ParsedConfirmedTransactionMetaResult),\n blockTime: optional(nullable(number())),\n version: optional(TransactionVersionStruct),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"getRecentBlockhash\" message\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead.\n */\nconst GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(\n pick({\n blockhash: string(),\n feeCalculator: pick({\n lamportsPerSignature: number(),\n }),\n }),\n);\n\n/**\n * Expected JSON RPC response for the \"getLatestBlockhash\" message\n */\nconst GetLatestBlockhashRpcResult = jsonRpcResultAndContext(\n pick({\n blockhash: string(),\n lastValidBlockHeight: number(),\n }),\n);\n\n/**\n * Expected JSON RPC response for the \"isBlockhashValid\" message\n */\nconst IsBlockhashValidRpcResult = jsonRpcResultAndContext(boolean());\n\nconst PerfSampleResult = pick({\n slot: number(),\n numTransactions: number(),\n numSlots: number(),\n samplePeriodSecs: number(),\n});\n\n/*\n * Expected JSON RPC response for \"getRecentPerformanceSamples\" message\n */\nconst GetRecentPerformanceSamplesRpcResult = jsonRpcResult(\n array(PerfSampleResult),\n);\n\n/**\n * Expected JSON RPC response for the \"getFeeCalculatorForBlockhash\" message\n */\nconst GetFeeCalculatorRpcResult = jsonRpcResultAndContext(\n nullable(\n pick({\n feeCalculator: pick({\n lamportsPerSignature: number(),\n }),\n }),\n ),\n);\n\n/**\n * Expected JSON RPC response for the \"requestAirdrop\" message\n */\nconst RequestAirdropRpcResult = jsonRpcResult(string());\n\n/**\n * Expected JSON RPC response for the \"sendTransaction\" message\n */\nconst SendTransactionRpcResult = jsonRpcResult(string());\n\n/**\n * Information about the latest slot being processed by a node\n */\nexport type SlotInfo = {\n /** Currently processing slot */\n slot: number;\n /** Parent of the current slot */\n parent: number;\n /** The root block of the current slot's fork */\n root: number;\n};\n\n/**\n * Parsed account data\n */\nexport type ParsedAccountData = {\n /** Name of the program that owns this account */\n program: string;\n /** Parsed account data */\n parsed: any;\n /** Space used by account data */\n space: number;\n};\n\n/**\n * Stake Activation data\n */\nexport type StakeActivationData = {\n /** the stake account's activation state */\n state: 'active' | 'inactive' | 'activating' | 'deactivating';\n /** stake active during the epoch */\n active: number;\n /** stake inactive during the epoch */\n inactive: number;\n};\n\n/**\n * Data slice argument for getProgramAccounts\n */\nexport type DataSlice = {\n /** offset of data slice */\n offset: number;\n /** length of data slice */\n length: number;\n};\n\n/**\n * Memory comparison filter for getProgramAccounts\n */\nexport type MemcmpFilter = {\n memcmp: {\n /** offset into program account data to start comparison */\n offset: number;\n } & (\n | {\n encoding?: 'base58'; // Base-58 is the default when not supplied.\n /** data to match, as base-58 encoded string and limited to less than 129 bytes */\n bytes: string;\n }\n | {\n encoding: 'base64';\n /** data to match, as base-64 encoded string */\n bytes: string;\n }\n );\n};\n\n/**\n * Data size comparison filter for getProgramAccounts\n */\nexport type DataSizeFilter = {\n /** Size of data for program account data length comparison */\n dataSize: number;\n};\n\n/**\n * A filter object for getProgramAccounts\n */\nexport type GetProgramAccountsFilter = MemcmpFilter | DataSizeFilter;\n\n/**\n * Configuration object for getProgramAccounts requests\n */\nexport type GetProgramAccountsConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Optional encoding for account data (default base64)\n * To use \"jsonParsed\" encoding, please refer to `getParsedProgramAccounts` in connection.ts\n * */\n encoding?: 'base64';\n /** Optional data slice to limit the returned account data */\n dataSlice?: DataSlice;\n /** Optional array of filters to apply to accounts */\n filters?: GetProgramAccountsFilter[];\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n /** wrap the result in an RpcResponse JSON object */\n withContext?: boolean;\n};\n\nexport type GetProgramAccountsResponse = readonly Readonly<{\n account: AccountInfo;\n /** the account Pubkey as base-58 encoded string */\n pubkey: PublicKey;\n}>[];\n\n/**\n * Configuration object for getParsedProgramAccounts\n */\nexport type GetParsedProgramAccountsConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Optional array of filters to apply to accounts */\n filters?: GetProgramAccountsFilter[];\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for getMultipleAccounts\n */\nexport type GetMultipleAccountsConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n /** Optional data slice to limit the returned account data */\n dataSlice?: DataSlice;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetStakeActivationConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** Epoch for which to calculate activation details. If parameter not provided, defaults to current epoch */\n epoch?: number;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetTokenAccountsByOwnerConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getStakeActivation`\n */\nexport type GetTransactionCountConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getNonce`\n */\nexport type GetNonceConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\n/**\n * Configuration object for `getNonceAndContext`\n */\nexport type GetNonceAndContextConfig = {\n /** Optional commitment level */\n commitment?: Commitment;\n /** The minimum slot that the request can be evaluated at */\n minContextSlot?: number;\n};\n\nexport type AccountSubscriptionConfig = Readonly<{\n /** Optional commitment level */\n commitment?: Commitment;\n /**\n * Encoding format for Account data\n * - `base58` is slow.\n * - `jsonParsed` encoding attempts to use program-specific state parsers to return more\n * human-readable and explicit account state data\n * - If `jsonParsed` is requested but a parser cannot be found, the field falls back to `base64`\n * encoding, detectable when the `data` field is type `string`.\n */\n encoding?: 'base58' | 'base64' | 'base64+zstd' | 'jsonParsed';\n}>;\n\nexport type ProgramAccountSubscriptionConfig = Readonly<{\n /** Optional commitment level */\n commitment?: Commitment;\n /**\n * Encoding format for Account data\n * - `base58` is slow.\n * - `jsonParsed` encoding attempts to use program-specific state parsers to return more\n * human-readable and explicit account state data\n * - If `jsonParsed` is requested but a parser cannot be found, the field falls back to `base64`\n * encoding, detectable when the `data` field is type `string`.\n */\n encoding?: 'base58' | 'base64' | 'base64+zstd' | 'jsonParsed';\n /**\n * Filter results using various filter objects\n * The resultant account must meet ALL filter criteria to be included in the returned results\n */\n filters?: GetProgramAccountsFilter[];\n}>;\n\n/**\n * Information describing an account\n */\nexport type AccountInfo = {\n /** `true` if this account's data contains a loaded program */\n executable: boolean;\n /** Identifier of the program that owns the account */\n owner: PublicKey;\n /** Number of lamports assigned to the account */\n lamports: number;\n /** Optional data assigned to the account */\n data: T;\n /** Optional rent epoch info for account */\n rentEpoch?: number;\n};\n\n/**\n * Account information identified by pubkey\n */\nexport type KeyedAccountInfo = {\n accountId: PublicKey;\n accountInfo: AccountInfo;\n};\n\n/**\n * Callback function for account change notifications\n */\nexport type AccountChangeCallback = (\n accountInfo: AccountInfo,\n context: Context,\n) => void;\n\n/**\n * Callback function for program account change notifications\n */\nexport type ProgramAccountChangeCallback = (\n keyedAccountInfo: KeyedAccountInfo,\n context: Context,\n) => void;\n\n/**\n * Callback function for slot change notifications\n */\nexport type SlotChangeCallback = (slotInfo: SlotInfo) => void;\n\n/**\n * Callback function for slot update notifications\n */\nexport type SlotUpdateCallback = (slotUpdate: SlotUpdate) => void;\n\n/**\n * Callback function for signature status notifications\n */\nexport type SignatureResultCallback = (\n signatureResult: SignatureResult,\n context: Context,\n) => void;\n\n/**\n * Signature status notification with transaction result\n */\nexport type SignatureStatusNotification = {\n type: 'status';\n result: SignatureResult;\n};\n\n/**\n * Signature received notification\n */\nexport type SignatureReceivedNotification = {\n type: 'received';\n};\n\n/**\n * Callback function for signature notifications\n */\nexport type SignatureSubscriptionCallback = (\n notification: SignatureStatusNotification | SignatureReceivedNotification,\n context: Context,\n) => void;\n\n/**\n * Signature subscription options\n */\nexport type SignatureSubscriptionOptions = {\n commitment?: Commitment;\n enableReceivedNotification?: boolean;\n};\n\n/**\n * Callback function for root change notifications\n */\nexport type RootChangeCallback = (root: number) => void;\n\n/**\n * @internal\n */\nconst LogsResult = pick({\n err: TransactionErrorResult,\n logs: array(string()),\n signature: string(),\n});\n\n/**\n * Logs result.\n */\nexport type Logs = {\n err: TransactionError | null;\n logs: string[];\n signature: string;\n};\n\n/**\n * Expected JSON RPC response for the \"logsNotification\" message.\n */\nconst LogsNotificationResult = pick({\n result: notificationResultAndContext(LogsResult),\n subscription: number(),\n});\n\n/**\n * Filter for log subscriptions.\n */\nexport type LogsFilter = PublicKey | 'all' | 'allWithVotes';\n\n/**\n * Callback function for log notifications.\n */\nexport type LogsCallback = (logs: Logs, ctx: Context) => void;\n\n/**\n * Signature result\n */\nexport type SignatureResult = {\n err: TransactionError | null;\n};\n\n/**\n * Transaction error\n */\nexport type TransactionError = {} | string;\n\n/**\n * Transaction confirmation status\n *
\n *   'processed': Transaction landed in a block which has reached 1 confirmation by the connected node\n *   'confirmed': Transaction landed in a block which has reached 1 confirmation by the cluster\n *   'finalized': Transaction landed in a block which has been finalized by the cluster\n * 
\n */\nexport type TransactionConfirmationStatus =\n | 'processed'\n | 'confirmed'\n | 'finalized';\n\n/**\n * Signature status\n */\nexport type SignatureStatus = {\n /** when the transaction was processed */\n slot: number;\n /** the number of blocks that have been confirmed and voted on in the fork containing `slot` */\n confirmations: number | null;\n /** transaction error, if any */\n err: TransactionError | null;\n /** cluster confirmation status, if data available. Possible responses: `processed`, `confirmed`, `finalized` */\n confirmationStatus?: TransactionConfirmationStatus;\n};\n\n/**\n * A confirmed signature with its status\n */\nexport type ConfirmedSignatureInfo = {\n /** the transaction signature */\n signature: string;\n /** when the transaction was processed */\n slot: number;\n /** error, if any */\n err: TransactionError | null;\n /** memo associated with the transaction, if any */\n memo: string | null;\n /** The unix timestamp of when the transaction was processed */\n blockTime?: number | null;\n /** Cluster confirmation status, if available. Possible values: `processed`, `confirmed`, `finalized` */\n confirmationStatus?: TransactionConfirmationStatus;\n};\n\n/**\n * An object defining headers to be passed to the RPC server\n */\nexport type HttpHeaders = {\n [header: string]: string;\n} & {\n // Prohibited headers; for internal use only.\n 'solana-client'?: never;\n};\n\n/**\n * The type of the JavaScript `fetch()` API\n */\nexport type FetchFn = typeof fetchImpl;\n\n/**\n * A callback used to augment the outgoing HTTP request\n */\nexport type FetchMiddleware = (\n info: Parameters[0],\n init: Parameters[1],\n fetch: (...a: Parameters) => void,\n) => void;\n\n/**\n * Configuration for instantiating a Connection\n */\nexport type ConnectionConfig = {\n /**\n * An `http.Agent` that will be used to manage socket connections (eg. to implement connection\n * persistence). Set this to `false` to create a connection that uses no agent. This applies to\n * Node environments only.\n */\n httpAgent?: NodeHttpAgent | NodeHttpsAgent | false;\n /** Optional commitment level */\n commitment?: Commitment;\n /** Optional endpoint URL to the fullnode JSON RPC PubSub WebSocket Endpoint */\n wsEndpoint?: string;\n /** Optional HTTP headers object */\n httpHeaders?: HttpHeaders;\n /** Optional custom fetch function */\n fetch?: FetchFn;\n /** Optional fetch middleware callback */\n fetchMiddleware?: FetchMiddleware;\n /** Optional Disable retrying calls when server responds with HTTP 429 (Too Many Requests) */\n disableRetryOnRateLimit?: boolean;\n /** time to allow for the server to initially process a transaction (in milliseconds) */\n confirmTransactionInitialTimeout?: number;\n};\n\n/** @internal */\nconst COMMON_HTTP_HEADERS = {\n 'solana-client': `js/${process.env.npm_package_version ?? 'UNKNOWN'}`,\n};\n\n/**\n * A connection to a fullnode JSON RPC endpoint\n */\nexport class Connection {\n /** @internal */ _commitment?: Commitment;\n /** @internal */ _confirmTransactionInitialTimeout?: number;\n /** @internal */ _rpcEndpoint: string;\n /** @internal */ _rpcWsEndpoint: string;\n /** @internal */ _rpcClient: RpcClient;\n /** @internal */ _rpcRequest: RpcRequest;\n /** @internal */ _rpcBatchRequest: RpcBatchRequest;\n /** @internal */ _rpcWebSocket: RpcWebSocketClient;\n /** @internal */ _rpcWebSocketConnected: boolean = false;\n /** @internal */ _rpcWebSocketHeartbeat: ReturnType<\n typeof setInterval\n > | null = null;\n /** @internal */ _rpcWebSocketIdleTimeout: ReturnType<\n typeof setTimeout\n > | null = null;\n /** @internal\n * A number that we increment every time an active connection closes.\n * Used to determine whether the same socket connection that was open\n * when an async operation started is the same one that's active when\n * its continuation fires.\n *\n */ private _rpcWebSocketGeneration: number = 0;\n\n /** @internal */ _disableBlockhashCaching: boolean = false;\n /** @internal */ _pollingBlockhash: boolean = false;\n /** @internal */ _blockhashInfo: {\n latestBlockhash: BlockhashWithExpiryBlockHeight | null;\n lastFetch: number;\n simulatedSignatures: Array;\n transactionSignatures: Array;\n } = {\n latestBlockhash: null,\n lastFetch: 0,\n transactionSignatures: [],\n simulatedSignatures: [],\n };\n\n /** @internal */ private _nextClientSubscriptionId: ClientSubscriptionId = 0;\n /** @internal */ private _subscriptionDisposeFunctionsByClientSubscriptionId: {\n [clientSubscriptionId: ClientSubscriptionId]:\n | SubscriptionDisposeFn\n | undefined;\n } = {};\n /** @internal */ private _subscriptionHashByClientSubscriptionId: {\n [clientSubscriptionId: ClientSubscriptionId]:\n | SubscriptionConfigHash\n | undefined;\n } = {};\n /** @internal */ private _subscriptionStateChangeCallbacksByHash: {\n [hash: SubscriptionConfigHash]:\n | Set\n | undefined;\n } = {};\n /** @internal */ private _subscriptionCallbacksByServerSubscriptionId: {\n [serverSubscriptionId: ServerSubscriptionId]:\n | Set\n | undefined;\n } = {};\n /** @internal */ private _subscriptionsByHash: {\n [hash: SubscriptionConfigHash]: Subscription | undefined;\n } = {};\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n /** @internal */ private _subscriptionsAutoDisposedByRpc: Set =\n new Set();\n\n /**\n * Establish a JSON RPC connection\n *\n * @param endpoint URL to the fullnode JSON RPC endpoint\n * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object\n */\n constructor(\n endpoint: string,\n commitmentOrConfig?: Commitment | ConnectionConfig,\n ) {\n let wsEndpoint;\n let httpHeaders;\n let fetch;\n let fetchMiddleware;\n let disableRetryOnRateLimit;\n let httpAgent;\n if (commitmentOrConfig && typeof commitmentOrConfig === 'string') {\n this._commitment = commitmentOrConfig;\n } else if (commitmentOrConfig) {\n this._commitment = commitmentOrConfig.commitment;\n this._confirmTransactionInitialTimeout =\n commitmentOrConfig.confirmTransactionInitialTimeout;\n wsEndpoint = commitmentOrConfig.wsEndpoint;\n httpHeaders = commitmentOrConfig.httpHeaders;\n fetch = commitmentOrConfig.fetch;\n fetchMiddleware = commitmentOrConfig.fetchMiddleware;\n disableRetryOnRateLimit = commitmentOrConfig.disableRetryOnRateLimit;\n httpAgent = commitmentOrConfig.httpAgent;\n }\n\n this._rpcEndpoint = assertEndpointUrl(endpoint);\n this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint);\n\n this._rpcClient = createRpcClient(\n endpoint,\n httpHeaders,\n fetch,\n fetchMiddleware,\n disableRetryOnRateLimit,\n httpAgent,\n );\n this._rpcRequest = createRpcRequest(this._rpcClient);\n this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient);\n\n this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, {\n autoconnect: false,\n max_reconnects: Infinity,\n });\n this._rpcWebSocket.on('open', this._wsOnOpen.bind(this));\n this._rpcWebSocket.on('error', this._wsOnError.bind(this));\n this._rpcWebSocket.on('close', this._wsOnClose.bind(this));\n this._rpcWebSocket.on(\n 'accountNotification',\n this._wsOnAccountNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'programNotification',\n this._wsOnProgramAccountNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'slotNotification',\n this._wsOnSlotNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'slotsUpdatesNotification',\n this._wsOnSlotUpdatesNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'signatureNotification',\n this._wsOnSignatureNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'rootNotification',\n this._wsOnRootNotification.bind(this),\n );\n this._rpcWebSocket.on(\n 'logsNotification',\n this._wsOnLogsNotification.bind(this),\n );\n }\n\n /**\n * The default commitment used for requests\n */\n get commitment(): Commitment | undefined {\n return this._commitment;\n }\n\n /**\n * The RPC endpoint\n */\n get rpcEndpoint(): string {\n return this._rpcEndpoint;\n }\n\n /**\n * Fetch the balance for the specified public key, return with context\n */\n async getBalanceAndContext(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetBalanceConfig,\n ): Promise> {\n /** @internal */\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the balance for the specified public key\n */\n async getBalance(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetBalanceConfig,\n ): Promise {\n return await this.getBalanceAndContext(publicKey, commitmentOrConfig)\n .then(x => x.value)\n .catch(e => {\n throw new Error(\n 'failed to get balance of account ' + publicKey.toBase58() + ': ' + e,\n );\n });\n }\n\n /**\n * Fetch the estimated production time of a block\n */\n async getBlockTime(slot: number): Promise {\n const unsafeRes = await this._rpcRequest('getBlockTime', [slot]);\n const res = create(unsafeRes, jsonRpcResult(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get block time for slot ${slot}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the lowest slot that the node has information about in its ledger.\n * This value may increase over time if the node is configured to purge older ledger data\n */\n async getMinimumLedgerSlot(): Promise {\n const unsafeRes = await this._rpcRequest('minimumLedgerSlot', []);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get minimum ledger slot',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the slot of the lowest confirmed block that has not been purged from the ledger\n */\n async getFirstAvailableBlock(): Promise {\n const unsafeRes = await this._rpcRequest('getFirstAvailableBlock', []);\n const res = create(unsafeRes, SlotRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get first available block',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch information about the current supply\n */\n async getSupply(\n config?: GetSupplyConfig | Commitment,\n ): Promise> {\n let configArg: GetSupplyConfig = {};\n if (typeof config === 'string') {\n configArg = {commitment: config};\n } else if (config) {\n configArg = {\n ...config,\n commitment: (config && config.commitment) || this.commitment,\n };\n } else {\n configArg = {\n commitment: this.commitment,\n };\n }\n\n const unsafeRes = await this._rpcRequest('getSupply', [configArg]);\n const res = create(unsafeRes, GetSupplyRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current supply of a token mint\n */\n async getTokenSupply(\n tokenMintAddress: PublicKey,\n commitment?: Commitment,\n ): Promise> {\n const args = this._buildArgs([tokenMintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenSupply', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get token supply');\n }\n return res.result;\n }\n\n /**\n * Fetch the current balance of a token account\n */\n async getTokenAccountBalance(\n tokenAddress: PublicKey,\n commitment?: Commitment,\n ): Promise> {\n const args = this._buildArgs([tokenAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenAccountBalance', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get token account balance',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the token accounts owned by the specified account\n *\n * @return {Promise}\n */\n async getTokenAccountsByOwner(\n ownerAddress: PublicKey,\n filter: TokenAccountsFilter,\n commitmentOrConfig?: Commitment | GetTokenAccountsByOwnerConfig,\n ): Promise> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n let _args: any[] = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({mint: filter.mint.toBase58()});\n } else {\n _args.push({programId: filter.programId.toBase58()});\n }\n\n const args = this._buildArgs(_args, commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get token accounts owned by account ${ownerAddress.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch parsed token accounts owned by the specified account\n *\n * @return {Promise}>>>}\n */\n async getParsedTokenAccountsByOwner(\n ownerAddress: PublicKey,\n filter: TokenAccountsFilter,\n commitment?: Commitment,\n ): Promise<\n RpcResponseAndContext<\n Array<{pubkey: PublicKey; account: AccountInfo}>\n >\n > {\n let _args: any[] = [ownerAddress.toBase58()];\n if ('mint' in filter) {\n _args.push({mint: filter.mint.toBase58()});\n } else {\n _args.push({programId: filter.programId.toBase58()});\n }\n\n const args = this._buildArgs(_args, commitment, 'jsonParsed');\n const unsafeRes = await this._rpcRequest('getTokenAccountsByOwner', args);\n const res = create(unsafeRes, GetParsedTokenAccountsByOwner);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get token accounts owned by account ${ownerAddress.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest accounts with their current balances\n */\n async getLargestAccounts(\n config?: GetLargestAccountsConfig,\n ): Promise>> {\n const arg = {\n ...config,\n commitment: (config && config.commitment) || this.commitment,\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = create(unsafeRes, GetLargestAccountsRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the 20 largest token accounts with their current balances\n * for a given mint.\n */\n async getTokenLargestAccounts(\n mintAddress: PublicKey,\n commitment?: Commitment,\n ): Promise>> {\n const args = this._buildArgs([mintAddress.toBase58()], commitment);\n const unsafeRes = await this._rpcRequest('getTokenLargestAccounts', args);\n const res = create(unsafeRes, GetTokenLargestAccountsResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get token largest accounts',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key, return with context\n */\n async getAccountInfoAndContext(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise | null>> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n 'base64',\n config,\n );\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(nullable(AccountInfoResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info about account ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch parsed account info for the specified public key\n */\n async getParsedAccountInfo(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise<\n RpcResponseAndContext | null>\n > {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getAccountInfo', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(nullable(ParsedAccountInfoResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info about account ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for the specified public key\n */\n async getAccountInfo(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise | null> {\n try {\n const res = await this.getAccountInfoAndContext(\n publicKey,\n commitmentOrConfig,\n );\n return res.value;\n } catch (e) {\n throw new Error(\n 'failed to get info about account ' + publicKey.toBase58() + ': ' + e,\n );\n }\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleParsedAccounts(\n publicKeys: PublicKey[],\n rawConfig?: GetMultipleAccountsConfig,\n ): Promise<\n RpcResponseAndContext<(AccountInfo | null)[]>\n > {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'jsonParsed', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult))),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for accounts ${keys}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys, return with context\n */\n async getMultipleAccountsInfoAndContext(\n publicKeys: PublicKey[],\n commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n ): Promise | null)[]>> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const keys = publicKeys.map(key => key.toBase58());\n const args = this._buildArgs([keys], commitment, 'base64', config);\n const unsafeRes = await this._rpcRequest('getMultipleAccounts', args);\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(nullable(AccountInfoResult))),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for accounts ${keys}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the account info for multiple accounts specified by an array of public keys\n */\n async getMultipleAccountsInfo(\n publicKeys: PublicKey[],\n commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n ): Promise<(AccountInfo | null)[]> {\n const res = await this.getMultipleAccountsInfoAndContext(\n publicKeys,\n commitmentOrConfig,\n );\n return res.value;\n }\n\n /**\n * Returns epoch activation information for a stake account that has been delegated\n *\n * @deprecated Deprecated since RPC v1.18; will be removed in a future version.\n */\n async getStakeActivation(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetStakeActivationConfig,\n epoch?: number,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment,\n undefined /* encoding */,\n {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch,\n },\n );\n\n const unsafeRes = await this._rpcRequest('getStakeActivation', args);\n const res = create(unsafeRes, jsonRpcResult(StakeActivationResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get Stake Activation ${publicKey.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment: GetProgramAccountsConfig &\n Readonly<{withContext: true}>,\n ): Promise>;\n // eslint-disable-next-line no-dupe-class-members\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetProgramAccountsConfig | Commitment,\n ): Promise;\n // eslint-disable-next-line no-dupe-class-members\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetProgramAccountsConfig | Commitment,\n ): Promise<\n | GetProgramAccountsResponse\n | RpcResponseAndContext\n > {\n const {commitment, config} =\n extractCommitmentFromConfig(configOrCommitment);\n const {encoding, ...configWithoutEncoding} = config || {};\n const args = this._buildArgs(\n [programId.toBase58()],\n commitment,\n encoding || 'base64',\n {\n ...configWithoutEncoding,\n ...(configWithoutEncoding.filters\n ? {\n filters: applyDefaultMemcmpEncodingToFilters(\n configWithoutEncoding.filters,\n ),\n }\n : null),\n },\n );\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const baseSchema = array(KeyedAccountInfoResult);\n const res =\n configWithoutEncoding.withContext === true\n ? create(unsafeRes, jsonRpcResultAndContext(baseSchema))\n : create(unsafeRes, jsonRpcResult(baseSchema));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get accounts owned by program ${programId.toBase58()}`,\n );\n }\n return res.result;\n }\n\n /**\n * Fetch and parse all the accounts owned by the specified program id\n *\n * @return {Promise}>>}\n */\n async getParsedProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetParsedProgramAccountsConfig | Commitment,\n ): Promise<\n Array<{\n pubkey: PublicKey;\n account: AccountInfo;\n }>\n > {\n const {commitment, config} =\n extractCommitmentFromConfig(configOrCommitment);\n const args = this._buildArgs(\n [programId.toBase58()],\n commitment,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getProgramAccounts', args);\n const res = create(\n unsafeRes,\n jsonRpcResult(array(KeyedParsedAccountInfoResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get accounts owned by program ${programId.toBase58()}`,\n );\n }\n return res.result;\n }\n\n confirmTransaction(\n strategy: TransactionConfirmationStrategy,\n commitment?: Commitment,\n ): Promise>;\n\n /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n // eslint-disable-next-line no-dupe-class-members\n confirmTransaction(\n strategy: TransactionSignature,\n commitment?: Commitment,\n ): Promise>;\n\n // eslint-disable-next-line no-dupe-class-members\n async confirmTransaction(\n strategy: TransactionConfirmationStrategy | TransactionSignature,\n commitment?: Commitment,\n ): Promise> {\n let rawSignature: string;\n\n if (typeof strategy == 'string') {\n rawSignature = strategy;\n } else {\n const config = strategy as TransactionConfirmationStrategy;\n\n if (config.abortSignal?.aborted) {\n return Promise.reject(config.abortSignal.reason);\n }\n rawSignature = config.signature;\n }\n\n let decodedSignature;\n\n try {\n decodedSignature = bs58.decode(rawSignature);\n } catch (err) {\n throw new Error('signature must be base58 encoded: ' + rawSignature);\n }\n\n assert(decodedSignature.length === 64, 'signature has invalid length');\n\n if (typeof strategy === 'string') {\n return await this.confirmTransactionUsingLegacyTimeoutStrategy({\n commitment: commitment || this.commitment,\n signature: rawSignature,\n });\n } else if ('lastValidBlockHeight' in strategy) {\n return await this.confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment: commitment || this.commitment,\n strategy,\n });\n } else {\n return await this.confirmTransactionUsingDurableNonceStrategy({\n commitment: commitment || this.commitment,\n strategy,\n });\n }\n }\n\n private getCancellationPromise(signal?: AbortSignal): Promise {\n return new Promise((_, reject) => {\n if (signal == null) {\n return;\n }\n if (signal.aborted) {\n reject(signal.reason);\n } else {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n });\n }\n });\n }\n\n private getTransactionConfirmationPromise({\n commitment,\n signature,\n }: {\n commitment?: Commitment;\n signature: string;\n }): {\n abortConfirmation(): void;\n confirmationPromise: Promise<{\n __type: TransactionStatus.PROCESSED;\n response: RpcResponseAndContext;\n }>;\n } {\n let signatureSubscriptionId: number | undefined;\n let disposeSignatureSubscriptionStateChangeObserver:\n | SubscriptionStateChangeDisposeFn\n | undefined;\n let done = false;\n const confirmationPromise = new Promise<{\n __type: TransactionStatus.PROCESSED;\n response: RpcResponseAndContext;\n }>((resolve, reject) => {\n try {\n signatureSubscriptionId = this.onSignature(\n signature,\n (result: SignatureResult, context: Context) => {\n signatureSubscriptionId = undefined;\n const response = {\n context,\n value: result,\n };\n resolve({__type: TransactionStatus.PROCESSED, response});\n },\n commitment,\n );\n const subscriptionSetupPromise = new Promise(\n resolveSubscriptionSetup => {\n if (signatureSubscriptionId == null) {\n resolveSubscriptionSetup();\n } else {\n disposeSignatureSubscriptionStateChangeObserver =\n this._onSubscriptionStateChange(\n signatureSubscriptionId,\n nextState => {\n if (nextState === 'subscribed') {\n resolveSubscriptionSetup();\n }\n },\n );\n }\n },\n );\n (async () => {\n await subscriptionSetupPromise;\n if (done) return;\n const response = await this.getSignatureStatus(signature);\n if (done) return;\n if (response == null) {\n return;\n }\n const {context, value} = response;\n if (value == null) {\n return;\n }\n if (value?.err) {\n reject(value.err);\n } else {\n switch (commitment) {\n case 'confirmed':\n case 'single':\n case 'singleGossip': {\n if (value.confirmationStatus === 'processed') {\n return;\n }\n break;\n }\n case 'finalized':\n case 'max':\n case 'root': {\n if (\n value.confirmationStatus === 'processed' ||\n value.confirmationStatus === 'confirmed'\n ) {\n return;\n }\n break;\n }\n // exhaust enums to ensure full coverage\n case 'processed':\n case 'recent':\n }\n done = true;\n resolve({\n __type: TransactionStatus.PROCESSED,\n response: {\n context,\n value,\n },\n });\n }\n })();\n } catch (err) {\n reject(err);\n }\n });\n const abortConfirmation = () => {\n if (disposeSignatureSubscriptionStateChangeObserver) {\n disposeSignatureSubscriptionStateChangeObserver();\n disposeSignatureSubscriptionStateChangeObserver = undefined;\n }\n if (signatureSubscriptionId != null) {\n this.removeSignatureListener(signatureSubscriptionId);\n signatureSubscriptionId = undefined;\n }\n };\n return {abortConfirmation, confirmationPromise};\n }\n\n private async confirmTransactionUsingBlockHeightExceedanceStrategy({\n commitment,\n strategy: {abortSignal, lastValidBlockHeight, signature},\n }: {\n commitment?: Commitment;\n strategy: BlockheightBasedTransactionConfirmationStrategy;\n }) {\n let done: boolean = false;\n const expiryPromise = new Promise<{\n __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED;\n }>(resolve => {\n const checkBlockHeight = async () => {\n try {\n const blockHeight = await this.getBlockHeight(commitment);\n return blockHeight;\n } catch (_e) {\n return -1;\n }\n };\n (async () => {\n let currentBlockHeight = await checkBlockHeight();\n if (done) return;\n while (currentBlockHeight <= lastValidBlockHeight) {\n await sleep(1000);\n if (done) return;\n currentBlockHeight = await checkBlockHeight();\n if (done) return;\n }\n resolve({__type: TransactionStatus.BLOCKHEIGHT_EXCEEDED});\n })();\n });\n const {abortConfirmation, confirmationPromise} =\n this.getTransactionConfirmationPromise({commitment, signature});\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result: RpcResponseAndContext;\n try {\n const outcome = await Promise.race([\n cancellationPromise,\n confirmationPromise,\n expiryPromise,\n ]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredBlockheightExceededError(signature);\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n\n private async confirmTransactionUsingDurableNonceStrategy({\n commitment,\n strategy: {\n abortSignal,\n minContextSlot,\n nonceAccountPubkey,\n nonceValue,\n signature,\n },\n }: {\n commitment?: Commitment;\n strategy: DurableNonceTransactionConfirmationStrategy;\n }) {\n let done: boolean = false;\n const expiryPromise = new Promise<{\n __type: TransactionStatus.NONCE_INVALID;\n slotInWhichNonceDidAdvance: number | null;\n }>(resolve => {\n let currentNonceValue: string | undefined = nonceValue;\n let lastCheckedSlot: number | null = null;\n const getCurrentNonceValue = async () => {\n try {\n const {context, value: nonceAccount} = await this.getNonceAndContext(\n nonceAccountPubkey,\n {\n commitment,\n minContextSlot,\n },\n );\n lastCheckedSlot = context.slot;\n return nonceAccount?.nonce;\n } catch (e) {\n // If for whatever reason we can't reach/read the nonce\n // account, just keep using the last-known value.\n return currentNonceValue;\n }\n };\n (async () => {\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n while (\n true // eslint-disable-line no-constant-condition\n ) {\n if (nonceValue !== currentNonceValue) {\n resolve({\n __type: TransactionStatus.NONCE_INVALID,\n slotInWhichNonceDidAdvance: lastCheckedSlot,\n });\n return;\n }\n await sleep(2000);\n if (done) return;\n currentNonceValue = await getCurrentNonceValue();\n if (done) return;\n }\n })();\n });\n const {abortConfirmation, confirmationPromise} =\n this.getTransactionConfirmationPromise({commitment, signature});\n const cancellationPromise = this.getCancellationPromise(abortSignal);\n let result: RpcResponseAndContext;\n try {\n const outcome = await Promise.race([\n cancellationPromise,\n confirmationPromise,\n expiryPromise,\n ]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n // Double check that the transaction is indeed unconfirmed.\n let signatureStatus:\n | RpcResponseAndContext\n | null\n | undefined;\n while (\n true // eslint-disable-line no-constant-condition\n ) {\n const status = await this.getSignatureStatus(signature);\n if (status == null) {\n break;\n }\n if (\n status.context.slot <\n (outcome.slotInWhichNonceDidAdvance ?? minContextSlot)\n ) {\n await sleep(400);\n continue;\n }\n signatureStatus = status;\n break;\n }\n if (signatureStatus?.value) {\n const commitmentForStatus = commitment || 'finalized';\n const {confirmationStatus} = signatureStatus.value;\n switch (commitmentForStatus) {\n case 'processed':\n case 'recent':\n if (\n confirmationStatus !== 'processed' &&\n confirmationStatus !== 'confirmed' &&\n confirmationStatus !== 'finalized'\n ) {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'confirmed':\n case 'single':\n case 'singleGossip':\n if (\n confirmationStatus !== 'confirmed' &&\n confirmationStatus !== 'finalized'\n ) {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n case 'finalized':\n case 'max':\n case 'root':\n if (confirmationStatus !== 'finalized') {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n break;\n default:\n // Exhaustive switch.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n ((_: never) => {})(commitmentForStatus);\n }\n result = {\n context: signatureStatus.context,\n value: {err: signatureStatus.value.err},\n };\n } else {\n throw new TransactionExpiredNonceInvalidError(signature);\n }\n }\n } finally {\n done = true;\n abortConfirmation();\n }\n return result;\n }\n\n private async confirmTransactionUsingLegacyTimeoutStrategy({\n commitment,\n signature,\n }: {\n commitment?: Commitment;\n signature: string;\n }) {\n let timeoutId;\n const expiryPromise = new Promise<{\n __type: TransactionStatus.TIMED_OUT;\n timeoutMs: number;\n }>(resolve => {\n let timeoutMs = this._confirmTransactionInitialTimeout || 60 * 1000;\n switch (commitment) {\n case 'processed':\n case 'recent':\n case 'single':\n case 'confirmed':\n case 'singleGossip': {\n timeoutMs = this._confirmTransactionInitialTimeout || 30 * 1000;\n break;\n }\n // exhaust enums to ensure full coverage\n case 'finalized':\n case 'max':\n case 'root':\n }\n timeoutId = setTimeout(\n () => resolve({__type: TransactionStatus.TIMED_OUT, timeoutMs}),\n timeoutMs,\n );\n });\n const {abortConfirmation, confirmationPromise} =\n this.getTransactionConfirmationPromise({\n commitment,\n signature,\n });\n let result: RpcResponseAndContext;\n try {\n const outcome = await Promise.race([confirmationPromise, expiryPromise]);\n if (outcome.__type === TransactionStatus.PROCESSED) {\n result = outcome.response;\n } else {\n throw new TransactionExpiredTimeoutError(\n signature,\n outcome.timeoutMs / 1000,\n );\n }\n } finally {\n clearTimeout(timeoutId);\n abortConfirmation();\n }\n return result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getClusterNodes(): Promise> {\n const unsafeRes = await this._rpcRequest('getClusterNodes', []);\n const res = create(unsafeRes, jsonRpcResult(array(ContactInfoResult)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes');\n }\n return res.result;\n }\n\n /**\n * Return the list of nodes that are currently participating in the cluster\n */\n async getVoteAccounts(commitment?: Commitment): Promise {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getVoteAccounts', args);\n const res = create(unsafeRes, GetVoteAccounts);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getSlot(\n commitmentOrConfig?: Commitment | GetSlotConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getSlot', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n return res.result;\n }\n\n /**\n * Fetch the current slot leader of the cluster\n */\n async getSlotLeader(\n commitmentOrConfig?: Commitment | GetSlotLeaderConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getSlotLeader', args);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leader');\n }\n return res.result;\n }\n\n /**\n * Fetch `limit` number of slot leaders starting from `startSlot`\n *\n * @param startSlot fetch slot leaders starting from this slot\n * @param limit number of slot leaders to return\n */\n async getSlotLeaders(\n startSlot: number,\n limit: number,\n ): Promise> {\n const args = [startSlot, limit];\n const unsafeRes = await this._rpcRequest('getSlotLeaders', args);\n const res = create(unsafeRes, jsonRpcResult(array(PublicKeyFromString)));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders');\n }\n return res.result;\n }\n\n /**\n * Fetch the current status of a signature\n */\n async getSignatureStatus(\n signature: TransactionSignature,\n config?: SignatureStatusConfig,\n ): Promise> {\n const {context, value: values} = await this.getSignatureStatuses(\n [signature],\n config,\n );\n assert(values.length === 1);\n const value = values[0];\n return {context, value};\n }\n\n /**\n * Fetch the current statuses of a batch of signatures\n */\n async getSignatureStatuses(\n signatures: Array,\n config?: SignatureStatusConfig,\n ): Promise>> {\n const params: any[] = [signatures];\n if (config) {\n params.push(config);\n }\n const unsafeRes = await this._rpcRequest('getSignatureStatuses', params);\n const res = create(unsafeRes, GetSignatureStatusesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get signature status');\n }\n return res.result;\n }\n\n /**\n * Fetch the current transaction count of the cluster\n */\n async getTransactionCount(\n commitmentOrConfig?: Commitment | GetTransactionCountConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getTransactionCount', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get transaction count',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the current total currency supply of the cluster in lamports\n *\n * @deprecated Deprecated since RPC v1.2.8. Please use {@link getSupply} instead.\n */\n async getTotalSupply(commitment?: Commitment): Promise {\n const result = await this.getSupply({\n commitment,\n excludeNonCirculatingAccountsList: true,\n });\n return result.value.total;\n }\n\n /**\n * Fetch the cluster InflationGovernor parameters\n */\n async getInflationGovernor(\n commitment?: Commitment,\n ): Promise {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getInflationGovernor', args);\n const res = create(unsafeRes, GetInflationGovernorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation');\n }\n return res.result;\n }\n\n /**\n * Fetch the inflation reward for a list of addresses for an epoch\n */\n async getInflationReward(\n addresses: PublicKey[],\n epoch?: number,\n commitmentOrConfig?: Commitment | GetInflationRewardConfig,\n ): Promise<(InflationReward | null)[]> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [addresses.map(pubkey => pubkey.toBase58())],\n commitment,\n undefined /* encoding */,\n {\n ...config,\n epoch: epoch != null ? epoch : config?.epoch,\n },\n );\n const unsafeRes = await this._rpcRequest('getInflationReward', args);\n const res = create(unsafeRes, GetInflationRewardResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward');\n }\n return res.result;\n }\n\n /**\n * Fetch the specific inflation values for the current epoch\n */\n async getInflationRate(): Promise {\n const unsafeRes = await this._rpcRequest('getInflationRate', []);\n const res = create(unsafeRes, GetInflationRateRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Info parameters\n */\n async getEpochInfo(\n commitmentOrConfig?: Commitment | GetEpochInfoConfig,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getEpochInfo', args);\n const res = create(unsafeRes, GetEpochInfoRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch info');\n }\n return res.result;\n }\n\n /**\n * Fetch the Epoch Schedule parameters\n */\n async getEpochSchedule(): Promise {\n const unsafeRes = await this._rpcRequest('getEpochSchedule', []);\n const res = create(unsafeRes, GetEpochScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule');\n }\n const epochSchedule = res.result;\n return new EpochSchedule(\n epochSchedule.slotsPerEpoch,\n epochSchedule.leaderScheduleSlotOffset,\n epochSchedule.warmup,\n epochSchedule.firstNormalEpoch,\n epochSchedule.firstNormalSlot,\n );\n }\n\n /**\n * Fetch the leader schedule for the current epoch\n * @return {Promise>}\n */\n async getLeaderSchedule(): Promise {\n const unsafeRes = await this._rpcRequest('getLeaderSchedule', []);\n const res = create(unsafeRes, GetLeaderScheduleRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule');\n }\n return res.result;\n }\n\n /**\n * Fetch the minimum balance needed to exempt an account of `dataLength`\n * size from rent\n */\n async getMinimumBalanceForRentExemption(\n dataLength: number,\n commitment?: Commitment,\n ): Promise {\n const args = this._buildArgs([dataLength], commitment);\n const unsafeRes = await this._rpcRequest(\n 'getMinimumBalanceForRentExemption',\n args,\n );\n const res = create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult);\n if ('error' in res) {\n console.warn('Unable to fetch minimum balance for rent exemption');\n return 0;\n }\n return res.result;\n }\n\n /**\n * Fetch a recent blockhash from the cluster, return with context\n * @return {Promise>}\n *\n * @deprecated Deprecated since RPC v1.9.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhashAndContext(commitment?: Commitment): Promise<\n RpcResponseAndContext<{\n blockhash: Blockhash;\n feeCalculator: FeeCalculator;\n }>\n > {\n const args = this._buildArgs([], commitment);\n const unsafeRes = await this._rpcRequest('getRecentBlockhash', args);\n const res = create(unsafeRes, GetRecentBlockhashAndContextRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch recent performance samples\n * @return {Promise>}\n */\n async getRecentPerformanceSamples(\n limit?: number,\n ): Promise> {\n const unsafeRes = await this._rpcRequest(\n 'getRecentPerformanceSamples',\n limit ? [limit] : [],\n );\n const res = create(unsafeRes, GetRecentPerformanceSamplesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get recent performance samples',\n );\n }\n\n return res.result;\n }\n\n /**\n * Fetch the fee calculator for a recent blockhash from the cluster, return with context\n *\n * @deprecated Deprecated since RPC v1.9.0. Please use {@link getFeeForMessage} instead.\n */\n async getFeeCalculatorForBlockhash(\n blockhash: Blockhash,\n commitment?: Commitment,\n ): Promise> {\n const args = this._buildArgs([blockhash], commitment);\n const unsafeRes = await this._rpcRequest(\n 'getFeeCalculatorForBlockhash',\n args,\n );\n\n const res = create(unsafeRes, GetFeeCalculatorRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator');\n }\n const {context, value} = res.result;\n return {\n context,\n value: value !== null ? value.feeCalculator : null,\n };\n }\n\n /**\n * Fetch the fee for a message from the cluster, return with context\n */\n async getFeeForMessage(\n message: VersionedMessage,\n commitment?: Commitment,\n ): Promise> {\n const wireMessage = toBuffer(message.serialize()).toString('base64');\n const args = this._buildArgs([wireMessage], commitment);\n const unsafeRes = await this._rpcRequest('getFeeForMessage', args);\n\n const res = create(unsafeRes, jsonRpcResultAndContext(nullable(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get fee for message');\n }\n if (res.result === null) {\n throw new Error('invalid blockhash');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of prioritization fees from recent blocks.\n */\n async getRecentPrioritizationFees(\n config?: GetRecentPrioritizationFeesConfig,\n ): Promise {\n const accounts = config?.lockedWritableAccounts?.map(key => key.toBase58());\n const args = accounts?.length ? [accounts] : [];\n const unsafeRes = await this._rpcRequest(\n 'getRecentPrioritizationFees',\n args,\n );\n const res = create(unsafeRes, GetRecentPrioritizationFeesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get recent prioritization fees',\n );\n }\n return res.result;\n }\n /**\n * Fetch a recent blockhash from the cluster\n * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>}\n *\n * @deprecated Deprecated since RPC v1.8.0. Please use {@link getLatestBlockhash} instead.\n */\n async getRecentBlockhash(\n commitment?: Commitment,\n ): Promise<{blockhash: Blockhash; feeCalculator: FeeCalculator}> {\n try {\n const res = await this.getRecentBlockhashAndContext(commitment);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhash(\n commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n ): Promise {\n try {\n const res = await this.getLatestBlockhashAndContext(commitmentOrConfig);\n return res.value;\n } catch (e) {\n throw new Error('failed to get recent blockhash: ' + e);\n }\n }\n\n /**\n * Fetch the latest blockhash from the cluster\n * @return {Promise}\n */\n async getLatestBlockhashAndContext(\n commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n ): Promise> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getLatestBlockhash', args);\n const res = create(unsafeRes, GetLatestBlockhashRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash');\n }\n return res.result;\n }\n\n /**\n * Returns whether a blockhash is still valid or not\n */\n async isBlockhashValid(\n blockhash: Blockhash,\n rawConfig?: IsBlockhashValidConfig,\n ): Promise> {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgs(\n [blockhash],\n commitment,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('isBlockhashValid', args);\n const res = create(unsafeRes, IsBlockhashValidRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to determine if the blockhash `' + blockhash + '`is valid',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the node version\n */\n async getVersion(): Promise {\n const unsafeRes = await this._rpcRequest('getVersion', []);\n const res = create(unsafeRes, jsonRpcResult(VersionResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get version');\n }\n return res.result;\n }\n\n /**\n * Fetch the genesis hash\n */\n async getGenesisHash(): Promise {\n const unsafeRes = await this._rpcRequest('getGenesisHash', []);\n const res = create(unsafeRes, jsonRpcResult(string()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash');\n }\n return res.result;\n }\n\n /**\n * Fetch a processed block from the cluster.\n *\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n async getBlock(\n slot: number,\n rawConfig?: GetBlockConfig,\n ): Promise;\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetBlockConfig & {transactionDetails: 'accounts'},\n ): Promise;\n\n /**\n * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by\n * setting the `maxSupportedTransactionVersion` property.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetBlockConfig & {transactionDetails: 'none'},\n ): Promise;\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'accounts'},\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'none'},\n ): Promise;\n\n /**\n * Fetch a processed block from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise<\n | VersionedBlockResponse\n | VersionedAccountsModeBlockResponse\n | VersionedNoneModeBlockResponse\n | null\n > {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment as Finality,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts': {\n const res = create(unsafeRes, GetAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none': {\n const res = create(unsafeRes, GetNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default: {\n const res = create(unsafeRes, GetBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n const {result} = res;\n return result\n ? {\n ...result,\n transactions: result.transactions.map(\n ({transaction, meta, version}) => ({\n meta,\n transaction: {\n ...transaction,\n message: versionedMessageFromResponse(\n version,\n transaction.message,\n ),\n },\n version,\n }),\n ),\n }\n : null;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(\n e as JSONRPCError,\n 'failed to get confirmed block',\n );\n }\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized block\n */\n async getParsedBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'accounts'},\n ): Promise;\n\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & {transactionDetails: 'none'},\n ): Promise;\n // eslint-disable-next-line no-dupe-class-members\n async getParsedBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise<\n | ParsedBlockResponse\n | ParsedAccountsModeBlockResponse\n | ParsedNoneModeBlockResponse\n | null\n > {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment as Finality,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getBlock', args);\n try {\n switch (config?.transactionDetails) {\n case 'accounts': {\n const res = create(unsafeRes, GetParsedAccountsModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n case 'none': {\n const res = create(unsafeRes, GetParsedNoneModeBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n default: {\n const res = create(unsafeRes, GetParsedBlockRpcResult);\n if ('error' in res) {\n throw res.error;\n }\n return res.result;\n }\n }\n } catch (e) {\n throw new SolanaJSONRPCError(e as JSONRPCError, 'failed to get block');\n }\n }\n\n /*\n * Returns the current block height of the node\n */\n getBlockHeight = (() => {\n const requestPromises: {[hash: string]: Promise} = {};\n return async (\n commitmentOrConfig?: Commitment | GetBlockHeightConfig,\n ): Promise => {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [],\n commitment,\n undefined /* encoding */,\n config,\n );\n const requestHash = fastStableStringify(args);\n requestPromises[requestHash] =\n requestPromises[requestHash] ??\n (async () => {\n try {\n const unsafeRes = await this._rpcRequest('getBlockHeight', args);\n const res = create(unsafeRes, jsonRpcResult(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get block height information',\n );\n }\n return res.result;\n } finally {\n delete requestPromises[requestHash];\n }\n })();\n return await requestPromises[requestHash];\n };\n })();\n\n /*\n * Returns recent block production information from the current or previous epoch\n */\n async getBlockProduction(\n configOrCommitment?: GetBlockProductionConfig | Commitment,\n ): Promise> {\n let extra: Omit | undefined;\n let commitment: Commitment | undefined;\n\n if (typeof configOrCommitment === 'string') {\n commitment = configOrCommitment;\n } else if (configOrCommitment) {\n const {commitment: c, ...rest} = configOrCommitment;\n commitment = c;\n extra = rest;\n }\n\n const args = this._buildArgs([], commitment, 'base64', extra);\n const unsafeRes = await this._rpcRequest('getBlockProduction', args);\n const res = create(unsafeRes, BlockProductionResponseStruct);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get block production information',\n );\n }\n\n return res.result;\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n *\n * @deprecated Instead, call `getTransaction` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n async getTransaction(\n signature: string,\n rawConfig?: GetTransactionConfig,\n ): Promise;\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransaction(\n signature: string,\n rawConfig: GetVersionedTransactionConfig,\n ): Promise;\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransaction(\n signature: string,\n rawConfig?: GetVersionedTransactionConfig,\n ): Promise {\n const {commitment, config} = extractCommitmentFromConfig(rawConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n undefined /* encoding */,\n config,\n );\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n\n const result = res.result;\n if (!result) return result;\n\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(\n result.version,\n result.transaction.message,\n ),\n },\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed or finalized transaction\n */\n async getParsedTransaction(\n signature: TransactionSignature,\n commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n ): Promise {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n 'jsonParsed',\n config,\n );\n const unsafeRes = await this._rpcRequest('getTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n */\n async getParsedTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n ): Promise<(ParsedTransactionWithMeta | null)[]> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n 'jsonParsed',\n config,\n );\n return {\n methodName: 'getTransaction',\n args,\n };\n });\n\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map((unsafeRes: any) => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n return res.result;\n });\n\n return res;\n }\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}.\n *\n * @deprecated Instead, call `getTransactions` using a\n * `GetVersionedTransactionConfig` by setting the\n * `maxSupportedTransactionVersion` property.\n */\n async getTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig?: GetTransactionConfig | Finality,\n ): Promise<(TransactionResponse | null)[]>;\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig: GetVersionedTransactionConfig | Finality,\n ): Promise<(VersionedTransactionResponse | null)[]>;\n\n /**\n * Fetch transaction details for a batch of confirmed transactions.\n * Similar to {@link getParsedTransactions} but returns a {@link\n * VersionedTransactionResponse}.\n */\n // eslint-disable-next-line no-dupe-class-members\n async getTransactions(\n signatures: TransactionSignature[],\n commitmentOrConfig: GetVersionedTransactionConfig | Finality,\n ): Promise<(VersionedTransactionResponse | null)[]> {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment as Finality,\n undefined /* encoding */,\n config,\n );\n return {\n methodName: 'getTransaction',\n args,\n };\n });\n\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map((unsafeRes: any) => {\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transactions');\n }\n const result = res.result;\n if (!result) return result;\n\n return {\n ...result,\n transaction: {\n ...result.transaction,\n message: versionedMessageFromResponse(\n result.version,\n result.transaction.message,\n ),\n },\n };\n });\n\n return res;\n }\n\n /**\n * Fetch a list of Transactions and transaction statuses from the cluster\n * for a confirmed block.\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlock} instead.\n */\n async getConfirmedBlock(\n slot: number,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed([slot], commitment);\n const unsafeRes = await this._rpcRequest('getConfirmedBlock', args);\n const res = create(unsafeRes, GetConfirmedBlockRpcResult);\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n\n const block = {\n ...result,\n transactions: result.transactions.map(({transaction, meta}) => {\n const message = new Message(transaction.message);\n return {\n meta,\n transaction: {\n ...transaction,\n message,\n },\n };\n }),\n };\n\n return {\n ...block,\n transactions: block.transactions.map(({transaction, meta}) => {\n return {\n meta,\n transaction: Transaction.populate(\n transaction.message,\n transaction.signatures,\n ),\n };\n }),\n };\n }\n\n /**\n * Fetch confirmed blocks between two slots\n */\n async getBlocks(\n startSlot: number,\n endSlot?: number,\n commitment?: Finality,\n ): Promise> {\n const args = this._buildArgsAtLeastConfirmed(\n endSlot !== undefined ? [startSlot, endSlot] : [startSlot],\n commitment,\n );\n const unsafeRes = await this._rpcRequest('getBlocks', args);\n const res = create(unsafeRes, jsonRpcResult(array(number())));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get blocks');\n }\n return res.result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a block, excluding rewards\n */\n async getBlockSignatures(\n slot: number,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment,\n undefined,\n {\n transactionDetails: 'signatures',\n rewards: false,\n },\n );\n const unsafeRes = await this._rpcRequest('getBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getBlockSignatures} instead.\n */\n async getConfirmedBlockSignatures(\n slot: number,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed(\n [slot],\n commitment,\n undefined,\n {\n transactionDetails: 'signatures',\n rewards: false,\n },\n );\n const unsafeRes = await this._rpcRequest('getConfirmedBlock', args);\n const res = create(unsafeRes, GetBlockSignaturesRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block');\n }\n const result = res.result;\n if (!result) {\n throw new Error('Confirmed block ' + slot + ' not found');\n }\n return result;\n }\n\n /**\n * Fetch a transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getTransaction} instead.\n */\n async getConfirmedTransaction(\n signature: TransactionSignature,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed([signature], commitment);\n const unsafeRes = await this._rpcRequest('getConfirmedTransaction', args);\n const res = create(unsafeRes, GetTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get transaction');\n }\n\n const result = res.result;\n if (!result) return result;\n\n const message = new Message(result.transaction.message);\n const signatures = result.transaction.signatures;\n return {\n ...result,\n transaction: Transaction.populate(message, signatures),\n };\n }\n\n /**\n * Fetch parsed transaction details for a confirmed transaction\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransaction} instead.\n */\n async getParsedConfirmedTransaction(\n signature: TransactionSignature,\n commitment?: Finality,\n ): Promise {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment,\n 'jsonParsed',\n );\n const unsafeRes = await this._rpcRequest('getConfirmedTransaction', args);\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get confirmed transaction',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch parsed transaction details for a batch of confirmed transactions\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getParsedTransactions} instead.\n */\n async getParsedConfirmedTransactions(\n signatures: TransactionSignature[],\n commitment?: Finality,\n ): Promise<(ParsedConfirmedTransaction | null)[]> {\n const batch = signatures.map(signature => {\n const args = this._buildArgsAtLeastConfirmed(\n [signature],\n commitment,\n 'jsonParsed',\n );\n return {\n methodName: 'getConfirmedTransaction',\n args,\n };\n });\n\n const unsafeRes = await this._rpcBatchRequest(batch);\n const res = unsafeRes.map((unsafeRes: any) => {\n const res = create(unsafeRes, GetParsedTransactionRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get confirmed transactions',\n );\n }\n return res.result;\n });\n\n return res;\n }\n\n /**\n * Fetch a list of all the confirmed signatures for transactions involving an address\n * within a specified slot range. Max range allowed is 10,000 slots.\n *\n * @deprecated Deprecated since RPC v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead.\n *\n * @param address queried address\n * @param startSlot start slot, inclusive\n * @param endSlot end slot, inclusive\n */\n async getConfirmedSignaturesForAddress(\n address: PublicKey,\n startSlot: number,\n endSlot: number,\n ): Promise> {\n let options: any = {};\n\n let firstAvailableBlock = await this.getFirstAvailableBlock();\n while (!('until' in options)) {\n startSlot--;\n if (startSlot <= 0 || startSlot < firstAvailableBlock) {\n break;\n }\n\n try {\n const block = await this.getConfirmedBlockSignatures(\n startSlot,\n 'finalized',\n );\n if (block.signatures.length > 0) {\n options.until =\n block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n\n let highestConfirmedRoot = await this.getSlot('finalized');\n while (!('before' in options)) {\n endSlot++;\n if (endSlot > highestConfirmedRoot) {\n break;\n }\n\n try {\n const block = await this.getConfirmedBlockSignatures(endSlot);\n if (block.signatures.length > 0) {\n options.before =\n block.signatures[block.signatures.length - 1].toString();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('skipped')) {\n continue;\n } else {\n throw err;\n }\n }\n }\n\n const confirmedSignatureInfo = await this.getConfirmedSignaturesForAddress2(\n address,\n options,\n );\n return confirmedSignatureInfo.map(info => info.signature);\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n * @deprecated Deprecated since RPC v1.7.0. Please use {@link getSignaturesForAddress} instead.\n */\n async getConfirmedSignaturesForAddress2(\n address: PublicKey,\n options?: ConfirmedSignaturesForAddress2Options,\n commitment?: Finality,\n ): Promise> {\n const args = this._buildArgsAtLeastConfirmed(\n [address.toBase58()],\n commitment,\n undefined,\n options,\n );\n const unsafeRes = await this._rpcRequest(\n 'getConfirmedSignaturesForAddress2',\n args,\n );\n const res = create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get confirmed signatures for address',\n );\n }\n return res.result;\n }\n\n /**\n * Returns confirmed signatures for transactions involving an\n * address backwards in time from the provided signature or most recent confirmed block\n *\n *\n * @param address queried address\n * @param options\n */\n async getSignaturesForAddress(\n address: PublicKey,\n options?: SignaturesForAddressOptions,\n commitment?: Finality,\n ): Promise> {\n const args = this._buildArgsAtLeastConfirmed(\n [address.toBase58()],\n commitment,\n undefined,\n options,\n );\n const unsafeRes = await this._rpcRequest('getSignaturesForAddress', args);\n const res = create(unsafeRes, GetSignaturesForAddressRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get signatures for address',\n );\n }\n return res.result;\n }\n\n async getAddressLookupTable(\n accountKey: PublicKey,\n config?: GetAccountInfoConfig,\n ): Promise> {\n const {context, value: accountInfo} = await this.getAccountInfoAndContext(\n accountKey,\n config,\n );\n\n let value = null;\n if (accountInfo !== null) {\n value = new AddressLookupTableAccount({\n key: accountKey,\n state: AddressLookupTableAccount.deserialize(accountInfo.data),\n });\n }\n\n return {\n context,\n value,\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster, return with context\n */\n async getNonceAndContext(\n nonceAccount: PublicKey,\n commitmentOrConfig?: Commitment | GetNonceAndContextConfig,\n ): Promise> {\n const {context, value: accountInfo} = await this.getAccountInfoAndContext(\n nonceAccount,\n commitmentOrConfig,\n );\n\n let value = null;\n if (accountInfo !== null) {\n value = NonceAccount.fromAccountData(accountInfo.data);\n }\n\n return {\n context,\n value,\n };\n }\n\n /**\n * Fetch the contents of a Nonce account from the cluster\n */\n async getNonce(\n nonceAccount: PublicKey,\n commitmentOrConfig?: Commitment | GetNonceConfig,\n ): Promise {\n return await this.getNonceAndContext(nonceAccount, commitmentOrConfig)\n .then(x => x.value)\n .catch(e => {\n throw new Error(\n 'failed to get nonce for account ' +\n nonceAccount.toBase58() +\n ': ' +\n e,\n );\n });\n }\n\n /**\n * Request an allocation of lamports to the specified address\n *\n * ```typescript\n * import { Connection, PublicKey, LAMPORTS_PER_SOL } from \"@solana/web3.js\";\n *\n * (async () => {\n * const connection = new Connection(\"https://api.testnet.solana.com\", \"confirmed\");\n * const myAddress = new PublicKey(\"2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM\");\n * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL);\n * await connection.confirmTransaction(signature);\n * })();\n * ```\n */\n async requestAirdrop(\n to: PublicKey,\n lamports: number,\n ): Promise {\n const unsafeRes = await this._rpcRequest('requestAirdrop', [\n to.toBase58(),\n lamports,\n ]);\n const res = create(unsafeRes, RequestAirdropRpcResult);\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `airdrop to ${to.toBase58()} failed`,\n );\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n async _blockhashWithExpiryBlockHeight(\n disableCache: boolean,\n ): Promise {\n if (!disableCache) {\n // Wait for polling to finish\n while (this._pollingBlockhash) {\n await sleep(100);\n }\n const timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch;\n const expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS;\n if (this._blockhashInfo.latestBlockhash !== null && !expired) {\n return this._blockhashInfo.latestBlockhash;\n }\n }\n\n return await this._pollNewBlockhash();\n }\n\n /**\n * @internal\n */\n async _pollNewBlockhash(): Promise {\n this._pollingBlockhash = true;\n try {\n const startTime = Date.now();\n const cachedLatestBlockhash = this._blockhashInfo.latestBlockhash;\n const cachedBlockhash = cachedLatestBlockhash\n ? cachedLatestBlockhash.blockhash\n : null;\n for (let i = 0; i < 50; i++) {\n const latestBlockhash = await this.getLatestBlockhash('finalized');\n\n if (cachedBlockhash !== latestBlockhash.blockhash) {\n this._blockhashInfo = {\n latestBlockhash,\n lastFetch: Date.now(),\n transactionSignatures: [],\n simulatedSignatures: [],\n };\n return latestBlockhash;\n }\n\n // Sleep for approximately half a slot\n await sleep(MS_PER_SLOT / 2);\n }\n\n throw new Error(\n `Unable to obtain a new blockhash after ${Date.now() - startTime}ms`,\n );\n } finally {\n this._pollingBlockhash = false;\n }\n }\n\n /**\n * get the stake minimum delegation\n */\n async getStakeMinimumDelegation(\n config?: GetStakeMinimumDelegationConfig,\n ): Promise> {\n const {commitment, config: configArg} = extractCommitmentFromConfig(config);\n const args = this._buildArgs([], commitment, 'base64', configArg);\n const unsafeRes = await this._rpcRequest('getStakeMinimumDelegation', args);\n const res = create(unsafeRes, jsonRpcResultAndContext(number()));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get stake minimum delegation`,\n );\n }\n return res.result;\n }\n\n /**\n * Simulate a transaction\n *\n * @deprecated Instead, call {@link simulateTransaction} with {@link\n * VersionedTransaction} and {@link SimulateTransactionConfig} parameters\n */\n simulateTransaction(\n transactionOrMessage: Transaction | Message,\n signers?: Array,\n includeAccounts?: boolean | Array,\n ): Promise>;\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n simulateTransaction(\n transaction: VersionedTransaction,\n config?: SimulateTransactionConfig,\n ): Promise>;\n\n /**\n * Simulate a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async simulateTransaction(\n transactionOrMessage: VersionedTransaction | Transaction | Message,\n configOrSigners?: SimulateTransactionConfig | Array,\n includeAccounts?: boolean | Array,\n ): Promise> {\n if ('message' in transactionOrMessage) {\n const versionedTx = transactionOrMessage;\n const wireTransaction = versionedTx.serialize();\n const encodedTransaction =\n Buffer.from(wireTransaction).toString('base64');\n if (Array.isArray(configOrSigners) || includeAccounts !== undefined) {\n throw new Error('Invalid arguments');\n }\n\n const config: any = configOrSigners || {};\n config.encoding = 'base64';\n if (!('commitment' in config)) {\n config.commitment = this.commitment;\n }\n\n if (\n configOrSigners &&\n typeof configOrSigners === 'object' &&\n 'innerInstructions' in configOrSigners\n ) {\n config.innerInstructions = configOrSigners.innerInstructions;\n }\n\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n throw new Error('failed to simulate transaction: ' + res.error.message);\n }\n return res.result;\n }\n\n let transaction;\n if (transactionOrMessage instanceof Transaction) {\n let originalTx: Transaction = transactionOrMessage;\n transaction = new Transaction();\n transaction.feePayer = originalTx.feePayer;\n transaction.instructions = transactionOrMessage.instructions;\n transaction.nonceInfo = originalTx.nonceInfo;\n transaction.signatures = originalTx.signatures;\n } else {\n transaction = Transaction.populate(transactionOrMessage);\n // HACK: this function relies on mutating the populated transaction\n transaction._message = transaction._json = undefined;\n }\n\n if (configOrSigners !== undefined && !Array.isArray(configOrSigners)) {\n throw new Error('Invalid arguments');\n }\n\n const signers = configOrSigners;\n if (transaction.nonceInfo && signers) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash =\n await this._blockhashWithExpiryBlockHeight(disableCache);\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n\n if (!signers) break;\n\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n\n const signature = transaction.signature.toString('base64');\n if (\n !this._blockhashInfo.simulatedSignatures.includes(signature) &&\n !this._blockhashInfo.transactionSignatures.includes(signature)\n ) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.simulatedSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n\n const message = transaction._compile();\n const signData = message.serialize();\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString('base64');\n const config: any = {\n encoding: 'base64',\n commitment: this.commitment,\n };\n\n if (includeAccounts) {\n const addresses = (\n Array.isArray(includeAccounts)\n ? includeAccounts\n : message.nonProgramIds()\n ).map(key => key.toBase58());\n\n config['accounts'] = {\n encoding: 'base64',\n addresses,\n };\n }\n\n if (signers) {\n config.sigVerify = true;\n }\n\n if (\n configOrSigners &&\n typeof configOrSigners === 'object' &&\n 'innerInstructions' in configOrSigners\n ) {\n config.innerInstructions = configOrSigners.innerInstructions;\n }\n\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('simulateTransaction', args);\n const res = create(unsafeRes, SimulatedTransactionResponseStruct);\n if ('error' in res) {\n let logs;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n if (logs && Array.isArray(logs)) {\n const traceIndent = '\\n ';\n const logTrace = traceIndent + logs.join(traceIndent);\n console.error(res.error.message, logTrace);\n }\n }\n\n throw new SendTransactionError({\n action: 'simulate',\n signature: '',\n transactionMessage: res.error.message,\n logs: logs,\n });\n }\n return res.result;\n }\n\n /**\n * Sign and send a transaction\n *\n * @deprecated Instead, call {@link sendTransaction} with a {@link\n * VersionedTransaction}\n */\n sendTransaction(\n transaction: Transaction,\n signers: Array,\n options?: SendOptions,\n ): Promise;\n\n /**\n * Send a signed transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n sendTransaction(\n transaction: VersionedTransaction,\n options?: SendOptions,\n ): Promise;\n\n /**\n * Sign and send a transaction\n */\n // eslint-disable-next-line no-dupe-class-members\n async sendTransaction(\n transaction: VersionedTransaction | Transaction,\n signersOrOptions?: Array | SendOptions,\n options?: SendOptions,\n ): Promise {\n if ('version' in transaction) {\n if (signersOrOptions && Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, signersOrOptions);\n }\n\n if (signersOrOptions === undefined || !Array.isArray(signersOrOptions)) {\n throw new Error('Invalid arguments');\n }\n\n const signers = signersOrOptions;\n if (transaction.nonceInfo) {\n transaction.sign(...signers);\n } else {\n let disableCache = this._disableBlockhashCaching;\n for (;;) {\n const latestBlockhash =\n await this._blockhashWithExpiryBlockHeight(disableCache);\n transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;\n transaction.recentBlockhash = latestBlockhash.blockhash;\n transaction.sign(...signers);\n if (!transaction.signature) {\n throw new Error('!signature'); // should never happen\n }\n\n const signature = transaction.signature.toString('base64');\n if (!this._blockhashInfo.transactionSignatures.includes(signature)) {\n // The signature of this transaction has not been seen before with the\n // current recentBlockhash, all done. Let's break\n this._blockhashInfo.transactionSignatures.push(signature);\n break;\n } else {\n // This transaction would be treated as duplicate (its derived signature\n // matched to one of already recorded signatures).\n // So, we must fetch a new blockhash for a different signature by disabling\n // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS).\n disableCache = true;\n }\n }\n }\n\n const wireTransaction = transaction.serialize();\n return await this.sendRawTransaction(wireTransaction, options);\n }\n\n /**\n * Send a transaction that has already been signed and serialized into the\n * wire format\n */\n async sendRawTransaction(\n rawTransaction: Buffer | Uint8Array | Array,\n options?: SendOptions,\n ): Promise {\n const encodedTransaction = toBuffer(rawTransaction).toString('base64');\n const result = await this.sendEncodedTransaction(\n encodedTransaction,\n options,\n );\n return result;\n }\n\n /**\n * Send a transaction that has already been signed, serialized into the\n * wire format, and encoded as a base64 string\n */\n async sendEncodedTransaction(\n encodedTransaction: string,\n options?: SendOptions,\n ): Promise {\n const config: any = {encoding: 'base64'};\n const skipPreflight = options && options.skipPreflight;\n const preflightCommitment =\n skipPreflight === true\n ? 'processed' // FIXME Remove when https://github.com/anza-xyz/agave/pull/483 is deployed.\n : (options && options.preflightCommitment) || this.commitment;\n\n if (options && options.maxRetries != null) {\n config.maxRetries = options.maxRetries;\n }\n if (options && options.minContextSlot != null) {\n config.minContextSlot = options.minContextSlot;\n }\n if (skipPreflight) {\n config.skipPreflight = skipPreflight;\n }\n if (preflightCommitment) {\n config.preflightCommitment = preflightCommitment;\n }\n\n const args = [encodedTransaction, config];\n const unsafeRes = await this._rpcRequest('sendTransaction', args);\n const res = create(unsafeRes, SendTransactionRpcResult);\n if ('error' in res) {\n let logs = undefined;\n if ('data' in res.error) {\n logs = res.error.data.logs;\n }\n\n throw new SendTransactionError({\n action: skipPreflight ? 'send' : 'simulate',\n signature: '',\n transactionMessage: res.error.message,\n logs: logs,\n });\n }\n return res.result;\n }\n\n /**\n * @internal\n */\n _wsOnOpen() {\n this._rpcWebSocketConnected = true;\n this._rpcWebSocketHeartbeat = setInterval(() => {\n // Ping server every 5s to prevent idle timeouts\n (async () => {\n try {\n await this._rpcWebSocket.notify('ping');\n // eslint-disable-next-line no-empty\n } catch {}\n })();\n }, 5000);\n this._updateSubscriptions();\n }\n\n /**\n * @internal\n */\n _wsOnError(err: Error) {\n this._rpcWebSocketConnected = false;\n console.error('ws error:', err.message);\n }\n\n /**\n * @internal\n */\n _wsOnClose(code: number) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketGeneration =\n (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER;\n if (this._rpcWebSocketIdleTimeout) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n }\n if (this._rpcWebSocketHeartbeat) {\n clearInterval(this._rpcWebSocketHeartbeat);\n this._rpcWebSocketHeartbeat = null;\n }\n\n if (code === 1000) {\n // explicit close, check if any subscriptions have been made since close\n this._updateSubscriptions();\n return;\n }\n\n // implicit close, prepare subscriptions for auto-reconnect\n this._subscriptionCallbacksByServerSubscriptionId = {};\n Object.entries(\n this._subscriptionsByHash as Record,\n ).forEach(([hash, subscription]) => {\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending',\n });\n });\n }\n\n /**\n * @internal\n */\n private _setSubscription(\n hash: SubscriptionConfigHash,\n nextSubscription: Subscription,\n ) {\n const prevState = this._subscriptionsByHash[hash]?.state;\n this._subscriptionsByHash[hash] = nextSubscription;\n if (prevState !== nextSubscription.state) {\n const stateChangeCallbacks =\n this._subscriptionStateChangeCallbacksByHash[hash];\n if (stateChangeCallbacks) {\n stateChangeCallbacks.forEach(cb => {\n try {\n cb(nextSubscription.state);\n // eslint-disable-next-line no-empty\n } catch {}\n });\n }\n }\n }\n\n /**\n * @internal\n */\n private _onSubscriptionStateChange(\n clientSubscriptionId: ClientSubscriptionId,\n callback: SubscriptionStateChangeCallback,\n ): SubscriptionStateChangeDisposeFn {\n const hash =\n this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n if (hash == null) {\n return () => {};\n }\n const stateChangeCallbacks = (this._subscriptionStateChangeCallbacksByHash[\n hash\n ] ||= new Set());\n stateChangeCallbacks.add(callback);\n return () => {\n stateChangeCallbacks.delete(callback);\n if (stateChangeCallbacks.size === 0) {\n delete this._subscriptionStateChangeCallbacksByHash[hash];\n }\n };\n }\n\n /**\n * @internal\n */\n async _updateSubscriptions() {\n if (Object.keys(this._subscriptionsByHash).length === 0) {\n if (this._rpcWebSocketConnected) {\n this._rpcWebSocketConnected = false;\n this._rpcWebSocketIdleTimeout = setTimeout(() => {\n this._rpcWebSocketIdleTimeout = null;\n try {\n this._rpcWebSocket.close();\n } catch (err) {\n // swallow error if socket has already been closed.\n if (err instanceof Error) {\n console.log(\n `Error when closing socket connection: ${err.message}`,\n );\n }\n }\n }, 500);\n }\n return;\n }\n\n if (this._rpcWebSocketIdleTimeout !== null) {\n clearTimeout(this._rpcWebSocketIdleTimeout);\n this._rpcWebSocketIdleTimeout = null;\n this._rpcWebSocketConnected = true;\n }\n\n if (!this._rpcWebSocketConnected) {\n this._rpcWebSocket.connect();\n return;\n }\n\n const activeWebSocketGeneration = this._rpcWebSocketGeneration;\n const isCurrentConnectionStillActive = () => {\n return activeWebSocketGeneration === this._rpcWebSocketGeneration;\n };\n\n await Promise.all(\n // Don't be tempted to change this to `Object.entries`. We call\n // `_updateSubscriptions` recursively when processing the state,\n // so it's important that we look up the *current* version of\n // each subscription, every time we process a hash.\n Object.keys(this._subscriptionsByHash).map(async hash => {\n const subscription = this._subscriptionsByHash[hash];\n if (subscription === undefined) {\n // This entry has since been deleted. Skip.\n return;\n }\n switch (subscription.state) {\n case 'pending':\n case 'unsubscribed':\n if (subscription.callbacks.size === 0) {\n /**\n * You can end up here when:\n *\n * - a subscription has recently unsubscribed\n * without having new callbacks added to it\n * while the unsubscribe was in flight, or\n * - when a pending subscription has its\n * listeners removed before a request was\n * sent to the server.\n *\n * Being that nobody is interested in this\n * subscription any longer, delete it.\n */\n delete this._subscriptionsByHash[hash];\n if (subscription.state === 'unsubscribed') {\n delete this._subscriptionCallbacksByServerSubscriptionId[\n subscription.serverSubscriptionId\n ];\n }\n await this._updateSubscriptions();\n return;\n }\n await (async () => {\n const {args, method} = subscription;\n try {\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribing',\n });\n const serverSubscriptionId: ServerSubscriptionId =\n (await this._rpcWebSocket.call(method, args)) as number;\n this._setSubscription(hash, {\n ...subscription,\n serverSubscriptionId,\n state: 'subscribed',\n });\n this._subscriptionCallbacksByServerSubscriptionId[\n serverSubscriptionId\n ] = subscription.callbacks;\n await this._updateSubscriptions();\n } catch (e) {\n if (e instanceof Error) {\n console.error(\n `${method} error for argument`,\n args,\n e.message,\n );\n }\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'pending',\n });\n await this._updateSubscriptions();\n }\n })();\n break;\n case 'subscribed':\n if (subscription.callbacks.size === 0) {\n // By the time we successfully set up a subscription\n // with the server, the client stopped caring about it.\n // Tear it down now.\n await (async () => {\n const {serverSubscriptionId, unsubscribeMethod} = subscription;\n if (\n this._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)\n ) {\n /**\n * Special case.\n * If we're dealing with a subscription that has been auto-\n * disposed by the RPC, then we can skip the RPC call to\n * tear down the subscription here.\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.delete(\n serverSubscriptionId,\n );\n } else {\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing',\n });\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribing',\n });\n try {\n await this._rpcWebSocket.call(unsubscribeMethod, [\n serverSubscriptionId,\n ]);\n } catch (e) {\n if (e instanceof Error) {\n console.error(`${unsubscribeMethod} error:`, e.message);\n }\n if (!isCurrentConnectionStillActive()) {\n return;\n }\n // TODO: Maybe add an 'errored' state or a retry limit?\n this._setSubscription(hash, {\n ...subscription,\n state: 'subscribed',\n });\n await this._updateSubscriptions();\n return;\n }\n }\n this._setSubscription(hash, {\n ...subscription,\n state: 'unsubscribed',\n });\n await this._updateSubscriptions();\n })();\n }\n break;\n case 'subscribing':\n case 'unsubscribing':\n break;\n }\n }),\n );\n }\n\n /**\n * @internal\n */\n private _handleServerNotification<\n TCallback extends SubscriptionConfig['callback'],\n >(\n serverSubscriptionId: ServerSubscriptionId,\n callbackArgs: Parameters,\n ): void {\n const callbacks =\n this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId];\n if (callbacks === undefined) {\n return;\n }\n callbacks.forEach(cb => {\n try {\n cb(\n // I failed to find a way to convince TypeScript that `cb` is of type\n // `TCallback` which is certainly compatible with `Parameters`.\n // See https://github.com/microsoft/TypeScript/issues/47615\n // @ts-ignore\n ...callbackArgs,\n );\n } catch (e) {\n console.error(e);\n }\n });\n }\n\n /**\n * @internal\n */\n _wsOnAccountNotification(notification: object) {\n const {result, subscription} = create(\n notification,\n AccountNotificationResult,\n );\n this._handleServerNotification(subscription, [\n result.value,\n result.context,\n ]);\n }\n\n /**\n * @internal\n */\n private _makeSubscription(\n subscriptionConfig: SubscriptionConfig,\n /**\n * When preparing `args` for a call to `_makeSubscription`, be sure\n * to carefully apply a default `commitment` property, if necessary.\n *\n * - If the user supplied a `commitment` use that.\n * - Otherwise, if the `Connection::commitment` is set, use that.\n * - Otherwise, set it to the RPC server default: `finalized`.\n *\n * This is extremely important to ensure that these two fundamentally\n * identical subscriptions produce the same identifying hash:\n *\n * - A subscription made without specifying a commitment.\n * - A subscription made where the commitment specified is the same\n * as the default applied to the subscription above.\n *\n * Example; these two subscriptions must produce the same hash:\n *\n * - An `accountSubscribe` subscription for `'PUBKEY'`\n * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment\n * `'finalized'`.\n *\n * See the 'making a subscription with defaulted params omitted' test\n * in `connection-subscriptions.ts` for more.\n */\n args: IWSRequestParams,\n ): ClientSubscriptionId {\n const clientSubscriptionId = this._nextClientSubscriptionId++;\n const hash = fastStableStringify([subscriptionConfig.method, args]);\n const existingSubscription = this._subscriptionsByHash[hash];\n if (existingSubscription === undefined) {\n this._subscriptionsByHash[hash] = {\n ...subscriptionConfig,\n args,\n callbacks: new Set([subscriptionConfig.callback]),\n state: 'pending',\n };\n } else {\n existingSubscription.callbacks.add(subscriptionConfig.callback);\n }\n this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash;\n this._subscriptionDisposeFunctionsByClientSubscriptionId[\n clientSubscriptionId\n ] = async () => {\n delete this._subscriptionDisposeFunctionsByClientSubscriptionId[\n clientSubscriptionId\n ];\n delete this._subscriptionHashByClientSubscriptionId[clientSubscriptionId];\n const subscription = this._subscriptionsByHash[hash];\n assert(\n subscription !== undefined,\n `Could not find a \\`Subscription\\` when tearing down client subscription #${clientSubscriptionId}`,\n );\n subscription.callbacks.delete(subscriptionConfig.callback);\n await this._updateSubscriptions();\n };\n this._updateSubscriptions();\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked whenever the specified account changes\n *\n * @param publicKey Public key of the account to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param config\n * @return subscription id\n */\n onAccountChange(\n publicKey: PublicKey,\n callback: AccountChangeCallback,\n config?: AccountSubscriptionConfig,\n ): ClientSubscriptionId;\n /** @deprecated Instead, pass in an {@link AccountSubscriptionConfig} */\n // eslint-disable-next-line no-dupe-class-members\n onAccountChange(\n publicKey: PublicKey,\n callback: AccountChangeCallback,\n commitment?: Commitment,\n ): ClientSubscriptionId;\n // eslint-disable-next-line no-dupe-class-members\n onAccountChange(\n publicKey: PublicKey,\n callback: AccountChangeCallback,\n commitmentOrConfig?: Commitment | AccountSubscriptionConfig,\n ): ClientSubscriptionId {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [publicKey.toBase58()],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n 'base64',\n config,\n );\n return this._makeSubscription(\n {\n callback,\n method: 'accountSubscribe',\n unsubscribeMethod: 'accountUnsubscribe',\n },\n args,\n );\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeAccountChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'account change',\n );\n }\n\n /**\n * @internal\n */\n _wsOnProgramAccountNotification(notification: Object) {\n const {result, subscription} = create(\n notification,\n ProgramAccountNotificationResult,\n );\n this._handleServerNotification(subscription, [\n {\n accountId: result.value.pubkey,\n accountInfo: result.value.account,\n },\n result.context,\n ]);\n }\n\n /**\n * Register a callback to be invoked whenever accounts owned by the\n * specified program change\n *\n * @param programId Public key of the program to monitor\n * @param callback Function to invoke whenever the account is changed\n * @param config\n * @return subscription id\n */\n onProgramAccountChange(\n programId: PublicKey,\n callback: ProgramAccountChangeCallback,\n config?: ProgramAccountSubscriptionConfig,\n ): ClientSubscriptionId;\n /** @deprecated Instead, pass in a {@link ProgramAccountSubscriptionConfig} */\n // eslint-disable-next-line no-dupe-class-members\n onProgramAccountChange(\n programId: PublicKey,\n callback: ProgramAccountChangeCallback,\n commitment?: Commitment,\n filters?: GetProgramAccountsFilter[],\n ): ClientSubscriptionId;\n // eslint-disable-next-line no-dupe-class-members\n onProgramAccountChange(\n programId: PublicKey,\n callback: ProgramAccountChangeCallback,\n commitmentOrConfig?: Commitment | ProgramAccountSubscriptionConfig,\n maybeFilters?: GetProgramAccountsFilter[],\n ): ClientSubscriptionId {\n const {commitment, config} =\n extractCommitmentFromConfig(commitmentOrConfig);\n const args = this._buildArgs(\n [programId.toBase58()],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n 'base64' /* encoding */,\n config\n ? config\n : maybeFilters\n ? {filters: applyDefaultMemcmpEncodingToFilters(maybeFilters)}\n : undefined /* extra */,\n );\n return this._makeSubscription(\n {\n callback,\n method: 'programSubscribe',\n unsubscribeMethod: 'programUnsubscribe',\n },\n args,\n );\n }\n\n /**\n * Deregister an account notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeProgramAccountChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'program account change',\n );\n }\n\n /**\n * Registers a callback to be invoked whenever logs are emitted.\n */\n onLogs(\n filter: LogsFilter,\n callback: LogsCallback,\n commitment?: Commitment,\n ): ClientSubscriptionId {\n const args = this._buildArgs(\n [typeof filter === 'object' ? {mentions: [filter.toString()]} : filter],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n );\n return this._makeSubscription(\n {\n callback,\n method: 'logsSubscribe',\n unsubscribeMethod: 'logsUnsubscribe',\n },\n args,\n );\n }\n\n /**\n * Deregister a logs callback.\n *\n * @param clientSubscriptionId client subscription id to deregister.\n */\n async removeOnLogsListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(clientSubscriptionId, 'logs');\n }\n\n /**\n * @internal\n */\n _wsOnLogsNotification(notification: Object) {\n const {result, subscription} = create(notification, LogsNotificationResult);\n this._handleServerNotification(subscription, [\n result.value,\n result.context,\n ]);\n }\n\n /**\n * @internal\n */\n _wsOnSlotNotification(notification: Object) {\n const {result, subscription} = create(notification, SlotNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot changes\n *\n * @param callback Function to invoke whenever the slot changes\n * @return subscription id\n */\n onSlotChange(callback: SlotChangeCallback): ClientSubscriptionId {\n return this._makeSubscription(\n {\n callback,\n method: 'slotSubscribe',\n unsubscribeMethod: 'slotUnsubscribe',\n },\n [] /* args */,\n );\n }\n\n /**\n * Deregister a slot notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSlotChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'slot change',\n );\n }\n\n /**\n * @internal\n */\n _wsOnSlotUpdatesNotification(notification: Object) {\n const {result, subscription} = create(\n notification,\n SlotUpdateNotificationResult,\n );\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s\n * may be useful to track live progress of a cluster.\n *\n * @param callback Function to invoke whenever the slot updates\n * @return subscription id\n */\n onSlotUpdate(callback: SlotUpdateCallback): ClientSubscriptionId {\n return this._makeSubscription(\n {\n callback,\n method: 'slotsUpdatesSubscribe',\n unsubscribeMethod: 'slotsUpdatesUnsubscribe',\n },\n [] /* args */,\n );\n }\n\n /**\n * Deregister a slot update notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSlotUpdateListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'slot update',\n );\n }\n\n /**\n * @internal\n */\n\n private async _unsubscribeClientSubscription(\n clientSubscriptionId: ClientSubscriptionId,\n subscriptionName: string,\n ) {\n const dispose =\n this._subscriptionDisposeFunctionsByClientSubscriptionId[\n clientSubscriptionId\n ];\n if (dispose) {\n await dispose();\n } else {\n console.warn(\n 'Ignored unsubscribe request because an active subscription with id ' +\n `\\`${clientSubscriptionId}\\` for '${subscriptionName}' events ` +\n 'could not be found.',\n );\n }\n }\n\n _buildArgs(\n args: Array,\n override?: Commitment,\n encoding?: 'jsonParsed' | 'base64',\n extra?: any,\n ): Array {\n const commitment = override || this._commitment;\n if (commitment || encoding || extra) {\n let options: any = {};\n if (encoding) {\n options.encoding = encoding;\n }\n if (commitment) {\n options.commitment = commitment;\n }\n if (extra) {\n options = Object.assign(options, extra);\n }\n args.push(options);\n }\n return args;\n }\n\n /**\n * @internal\n */\n _buildArgsAtLeastConfirmed(\n args: Array,\n override?: Finality,\n encoding?: 'jsonParsed' | 'base64',\n extra?: any,\n ): Array {\n const commitment = override || this._commitment;\n if (commitment && !['confirmed', 'finalized'].includes(commitment)) {\n throw new Error(\n 'Using Connection with default commitment: `' +\n this._commitment +\n '`, but method requires at least `confirmed`',\n );\n }\n return this._buildArgs(args, override, encoding, extra);\n }\n\n /**\n * @internal\n */\n _wsOnSignatureNotification(notification: Object) {\n const {result, subscription} = create(\n notification,\n SignatureNotificationResult,\n );\n if (result.value !== 'receivedSignature') {\n /**\n * Special case.\n * After a signature is processed, RPCs automatically dispose of the\n * subscription on the server side. We need to track which of these\n * subscriptions have been disposed in such a way, so that we know\n * whether the client is dealing with a not-yet-processed signature\n * (in which case we must tear down the server subscription) or an\n * already-processed signature (in which case the client can simply\n * clear out the subscription locally without telling the server).\n *\n * NOTE: There is a proposal to eliminate this special case, here:\n * https://github.com/solana-labs/solana/issues/18892\n */\n this._subscriptionsAutoDisposedByRpc.add(subscription);\n }\n this._handleServerNotification(\n subscription,\n result.value === 'receivedSignature'\n ? [{type: 'received'}, result.context]\n : [{type: 'status', result: result.value}, result.context],\n );\n }\n\n /**\n * Register a callback to be invoked upon signature updates\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param commitment Specify the commitment level signature must reach before notification\n * @return subscription id\n */\n onSignature(\n signature: TransactionSignature,\n callback: SignatureResultCallback,\n commitment?: Commitment,\n ): ClientSubscriptionId {\n const args = this._buildArgs(\n [signature],\n commitment || this._commitment || 'finalized', // Apply connection/server default.\n );\n const clientSubscriptionId = this._makeSubscription(\n {\n callback: (notification, context) => {\n if (notification.type === 'status') {\n callback(notification.result, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe',\n },\n args,\n );\n return clientSubscriptionId;\n }\n\n /**\n * Register a callback to be invoked when a transaction is\n * received and/or processed.\n *\n * @param signature Transaction signature string in base 58\n * @param callback Function to invoke on signature notifications\n * @param options Enable received notifications and set the commitment\n * level that signature must reach before notification\n * @return subscription id\n */\n onSignatureWithOptions(\n signature: TransactionSignature,\n callback: SignatureSubscriptionCallback,\n options?: SignatureSubscriptionOptions,\n ): ClientSubscriptionId {\n const {commitment, ...extra} = {\n ...options,\n commitment:\n (options && options.commitment) || this._commitment || 'finalized', // Apply connection/server default.\n };\n const args = this._buildArgs(\n [signature],\n commitment,\n undefined /* encoding */,\n extra,\n );\n const clientSubscriptionId = this._makeSubscription(\n {\n callback: (notification, context) => {\n callback(notification, context);\n // Signatures subscriptions are auto-removed by the RPC service\n // so no need to explicitly send an unsubscribe message.\n try {\n this.removeSignatureListener(clientSubscriptionId);\n // eslint-disable-next-line no-empty\n } catch (_err) {\n // Already removed.\n }\n },\n method: 'signatureSubscribe',\n unsubscribeMethod: 'signatureUnsubscribe',\n },\n args,\n );\n return clientSubscriptionId;\n }\n\n /**\n * Deregister a signature notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeSignatureListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'signature result',\n );\n }\n\n /**\n * @internal\n */\n _wsOnRootNotification(notification: Object) {\n const {result, subscription} = create(notification, RootNotificationResult);\n this._handleServerNotification(subscription, [result]);\n }\n\n /**\n * Register a callback to be invoked upon root changes\n *\n * @param callback Function to invoke whenever the root changes\n * @return subscription id\n */\n onRootChange(callback: RootChangeCallback): ClientSubscriptionId {\n return this._makeSubscription(\n {\n callback,\n method: 'rootSubscribe',\n unsubscribeMethod: 'rootUnsubscribe',\n },\n [] /* args */,\n );\n }\n\n /**\n * Deregister a root notification callback\n *\n * @param clientSubscriptionId client subscription id to deregister\n */\n async removeRootChangeListener(\n clientSubscriptionId: ClientSubscriptionId,\n ): Promise {\n await this._unsubscribeClientSubscription(\n clientSubscriptionId,\n 'root change',\n );\n }\n}\n","import {generateKeypair, getPublicKey, Ed25519Keypair} from './utils/ed25519';\nimport {PublicKey} from './publickey';\n\n/**\n * Keypair signer interface\n */\nexport interface Signer {\n publicKey: PublicKey;\n secretKey: Uint8Array;\n}\n\n/**\n * An account keypair used for signing transactions.\n */\nexport class Keypair {\n private _keypair: Ed25519Keypair;\n\n /**\n * Create a new keypair instance.\n * Generate random keypair if no {@link Ed25519Keypair} is provided.\n *\n * @param {Ed25519Keypair} keypair ed25519 keypair\n */\n constructor(keypair?: Ed25519Keypair) {\n this._keypair = keypair ?? generateKeypair();\n }\n\n /**\n * Generate a new random keypair\n *\n * @returns {Keypair} Keypair\n */\n static generate(): Keypair {\n return new Keypair(generateKeypair());\n }\n\n /**\n * Create a keypair from a raw secret key byte array.\n *\n * This method should only be used to recreate a keypair from a previously\n * generated secret key. Generating keypairs from a random seed should be done\n * with the {@link Keypair.fromSeed} method.\n *\n * @throws error if the provided secret key is invalid and validation is not skipped.\n *\n * @param secretKey secret key byte array\n * @param options skip secret key validation\n *\n * @returns {Keypair} Keypair\n */\n static fromSecretKey(\n secretKey: Uint8Array,\n options?: {skipValidation?: boolean},\n ): Keypair {\n if (secretKey.byteLength !== 64) {\n throw new Error('bad secret key size');\n }\n const publicKey = secretKey.slice(32, 64);\n if (!options || !options.skipValidation) {\n const privateScalar = secretKey.slice(0, 32);\n const computedPublicKey = getPublicKey(privateScalar);\n for (let ii = 0; ii < 32; ii++) {\n if (publicKey[ii] !== computedPublicKey[ii]) {\n throw new Error('provided secretKey is invalid');\n }\n }\n }\n return new Keypair({publicKey, secretKey});\n }\n\n /**\n * Generate a keypair from a 32 byte seed.\n *\n * @param seed seed byte array\n *\n * @returns {Keypair} Keypair\n */\n static fromSeed(seed: Uint8Array): Keypair {\n const publicKey = getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed);\n secretKey.set(publicKey, 32);\n return new Keypair({publicKey, secretKey});\n }\n\n /**\n * The public key for this keypair\n *\n * @returns {PublicKey} PublicKey\n */\n get publicKey(): PublicKey {\n return new PublicKey(this._keypair.publicKey);\n }\n\n /**\n * The raw secret key for this keypair\n * @returns {Uint8Array} Secret key in an array of Uint8 bytes\n */\n get secretKey(): Uint8Array {\n return new Uint8Array(this._keypair.secretKey);\n }\n}\n","import {toBufferLE} from 'bigint-buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport * as Layout from '../../layout';\nimport {PublicKey} from '../../publickey';\nimport * as bigintLayout from '../../utils/bigint';\nimport {SystemProgram} from '../system';\nimport {TransactionInstruction} from '../../transaction';\nimport {decodeData, encodeData, IInstructionInputData} from '../../instruction';\n\nexport * from './state';\n\nexport type CreateLookupTableParams = {\n /** Account used to derive and control the new address lookup table. */\n authority: PublicKey;\n /** Account that will fund the new address lookup table. */\n payer: PublicKey;\n /** A recent slot must be used in the derivation path for each initialized table. */\n recentSlot: bigint | number;\n};\n\nexport type FreezeLookupTableParams = {\n /** Address lookup table account to freeze. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n};\n\nexport type ExtendLookupTableParams = {\n /** Address lookup table account to extend. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n /** Account that will fund the table reallocation.\n * Not required if the reallocation has already been funded. */\n payer?: PublicKey;\n /** List of Public Keys to be added to the lookup table. */\n addresses: Array;\n};\n\nexport type DeactivateLookupTableParams = {\n /** Address lookup table account to deactivate. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n};\n\nexport type CloseLookupTableParams = {\n /** Address lookup table account to close. */\n lookupTable: PublicKey;\n /** Account which is the current authority. */\n authority: PublicKey;\n /** Recipient of closed account lamports. */\n recipient: PublicKey;\n};\n\n/**\n * An enumeration of valid LookupTableInstructionType's\n */\nexport type LookupTableInstructionType =\n | 'CreateLookupTable'\n | 'ExtendLookupTable'\n | 'CloseLookupTable'\n | 'FreezeLookupTable'\n | 'DeactivateLookupTable';\n\ntype LookupTableInstructionInputData = {\n CreateLookupTable: IInstructionInputData &\n Readonly<{\n recentSlot: bigint;\n bumpSeed: number;\n }>;\n FreezeLookupTable: IInstructionInputData;\n ExtendLookupTable: IInstructionInputData &\n Readonly<{\n numberOfAddresses: bigint;\n addresses: Array;\n }>;\n DeactivateLookupTable: IInstructionInputData;\n CloseLookupTable: IInstructionInputData;\n};\n\n/**\n * An enumeration of valid address lookup table InstructionType's\n * @internal\n */\nexport const LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({\n CreateLookupTable: {\n index: 0,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['CreateLookupTable']\n >([\n BufferLayout.u32('instruction'),\n bigintLayout.u64('recentSlot'),\n BufferLayout.u8('bumpSeed'),\n ]),\n },\n FreezeLookupTable: {\n index: 1,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['FreezeLookupTable']\n >([BufferLayout.u32('instruction')]),\n },\n ExtendLookupTable: {\n index: 2,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['ExtendLookupTable']\n >([\n BufferLayout.u32('instruction'),\n bigintLayout.u64(),\n BufferLayout.seq(\n Layout.publicKey(),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'addresses',\n ),\n ]),\n },\n DeactivateLookupTable: {\n index: 3,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['DeactivateLookupTable']\n >([BufferLayout.u32('instruction')]),\n },\n CloseLookupTable: {\n index: 4,\n layout: BufferLayout.struct<\n LookupTableInstructionInputData['CloseLookupTable']\n >([BufferLayout.u32('instruction')]),\n },\n});\n\nexport class AddressLookupTableInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): LookupTableInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const index = instructionTypeLayout.decode(instruction.data);\n\n let type: LookupTableInstructionType | undefined;\n for (const [layoutType, layout] of Object.entries(\n LOOKUP_TABLE_INSTRUCTION_LAYOUTS,\n )) {\n if ((layout as any).index == index) {\n type = layoutType as LookupTableInstructionType;\n break;\n }\n }\n if (!type) {\n throw new Error(\n 'Invalid Instruction. Should be a LookupTable Instruction',\n );\n }\n return type;\n }\n\n static decodeCreateLookupTable(\n instruction: TransactionInstruction,\n ): CreateLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 4);\n\n const {recentSlot} = decodeData(\n LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable,\n instruction.data,\n );\n\n return {\n authority: instruction.keys[1].pubkey,\n payer: instruction.keys[2].pubkey,\n recentSlot: Number(recentSlot),\n };\n }\n\n static decodeExtendLookupTable(\n instruction: TransactionInstruction,\n ): ExtendLookupTableParams {\n this.checkProgramId(instruction.programId);\n if (instruction.keys.length < 2) {\n throw new Error(\n `invalid instruction; found ${instruction.keys.length} keys, expected at least 2`,\n );\n }\n\n const {addresses} = decodeData(\n LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable,\n instruction.data,\n );\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n payer:\n instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined,\n addresses: addresses.map(buffer => new PublicKey(buffer)),\n };\n }\n\n static decodeCloseLookupTable(\n instruction: TransactionInstruction,\n ): CloseLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 3);\n\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n recipient: instruction.keys[2].pubkey,\n };\n }\n\n static decodeFreezeLookupTable(\n instruction: TransactionInstruction,\n ): FreezeLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n };\n }\n\n static decodeDeactivateLookupTable(\n instruction: TransactionInstruction,\n ): DeactivateLookupTableParams {\n this.checkProgramId(instruction.programId);\n this.checkKeysLength(instruction.keys, 2);\n\n return {\n lookupTable: instruction.keys[0].pubkey,\n authority: instruction.keys[1].pubkey,\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(AddressLookupTableProgram.programId)) {\n throw new Error(\n 'invalid instruction; programId is not AddressLookupTable Program',\n );\n }\n }\n /**\n * @internal\n */\n static checkKeysLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\nexport class AddressLookupTableProgram {\n /**\n * @internal\n */\n constructor() {}\n\n static programId: PublicKey = new PublicKey(\n 'AddressLookupTab1e1111111111111111111111111',\n );\n\n static createLookupTable(params: CreateLookupTableParams) {\n const [lookupTableAddress, bumpSeed] = PublicKey.findProgramAddressSync(\n [params.authority.toBuffer(), toBufferLE(BigInt(params.recentSlot), 8)],\n this.programId,\n );\n\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable;\n const data = encodeData(type, {\n recentSlot: BigInt(params.recentSlot),\n bumpSeed: bumpSeed,\n });\n\n const keys = [\n {\n pubkey: lookupTableAddress,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n {\n pubkey: params.payer,\n isSigner: true,\n isWritable: true,\n },\n {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n ];\n\n return [\n new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n }),\n lookupTableAddress,\n ] as [TransactionInstruction, PublicKey];\n }\n\n static freezeLookupTable(params: FreezeLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable;\n const data = encodeData(type);\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n\n static extendLookupTable(params: ExtendLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable;\n const data = encodeData(type, {\n addresses: params.addresses.map(addr => addr.toBytes()),\n });\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n if (params.payer) {\n keys.push(\n {\n pubkey: params.payer,\n isSigner: true,\n isWritable: true,\n },\n {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n );\n }\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n\n static deactivateLookupTable(params: DeactivateLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable;\n const data = encodeData(type);\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n\n static closeLookupTable(params: CloseLookupTableParams) {\n const type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable;\n const data = encodeData(type);\n\n const keys = [\n {\n pubkey: params.lookupTable,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: params.authority,\n isSigner: true,\n isWritable: false,\n },\n {\n pubkey: params.recipient,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys: keys,\n data: data,\n });\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport {u64} from '../utils/bigint';\n\n/**\n * Compute Budget Instruction class\n */\nexport class ComputeBudgetInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a compute budget instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): ComputeBudgetInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u8('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: ComputeBudgetInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS,\n )) {\n if (layout.index == typeIndex) {\n type = ixType as ComputeBudgetInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error(\n 'Instruction type incorrect; not a ComputeBudgetInstruction',\n );\n }\n\n return type;\n }\n\n /**\n * Decode request units compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestUnits(\n instruction: TransactionInstruction,\n ): RequestUnitsParams {\n this.checkProgramId(instruction.programId);\n const {units, additionalFee} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits,\n instruction.data,\n );\n return {units, additionalFee};\n }\n\n /**\n * Decode request heap frame compute budget instruction and retrieve the instruction params.\n */\n static decodeRequestHeapFrame(\n instruction: TransactionInstruction,\n ): RequestHeapFrameParams {\n this.checkProgramId(instruction.programId);\n const {bytes} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame,\n instruction.data,\n );\n return {bytes};\n }\n\n /**\n * Decode set compute unit limit compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitLimit(\n instruction: TransactionInstruction,\n ): SetComputeUnitLimitParams {\n this.checkProgramId(instruction.programId);\n const {units} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit,\n instruction.data,\n );\n return {units};\n }\n\n /**\n * Decode set compute unit price compute budget instruction and retrieve the instruction params.\n */\n static decodeSetComputeUnitPrice(\n instruction: TransactionInstruction,\n ): SetComputeUnitPriceParams {\n this.checkProgramId(instruction.programId);\n const {microLamports} = decodeData(\n COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice,\n instruction.data,\n );\n return {microLamports};\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(ComputeBudgetProgram.programId)) {\n throw new Error(\n 'invalid instruction; programId is not ComputeBudgetProgram',\n );\n }\n }\n}\n\n/**\n * An enumeration of valid ComputeBudgetInstructionType's\n */\nexport type ComputeBudgetInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof ComputeBudgetInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'RequestUnits'\n | 'RequestHeapFrame'\n | 'SetComputeUnitLimit'\n | 'SetComputeUnitPrice';\n\ntype ComputeBudgetInstructionInputData = {\n RequestUnits: IInstructionInputData & Readonly;\n RequestHeapFrame: IInstructionInputData & Readonly;\n SetComputeUnitLimit: IInstructionInputData &\n Readonly;\n SetComputeUnitPrice: IInstructionInputData &\n Readonly;\n};\n\n/**\n * Request units instruction params\n */\nexport interface RequestUnitsParams {\n /** Units to request for transaction-wide compute */\n units: number;\n /** Prioritization fee lamports */\n additionalFee: number;\n}\n\n/**\n * Request heap frame instruction params\n */\nexport type RequestHeapFrameParams = {\n /** Requested transaction-wide program heap size in bytes. Must be multiple of 1024. Applies to each program, including CPIs. */\n bytes: number;\n};\n\n/**\n * Set compute unit limit instruction params\n */\nexport interface SetComputeUnitLimitParams {\n /** Transaction-wide compute unit limit */\n units: number;\n}\n\n/**\n * Set compute unit price instruction params\n */\nexport interface SetComputeUnitPriceParams {\n /** Transaction compute unit price used for prioritization fees */\n microLamports: number | bigint;\n}\n\n/**\n * An enumeration of valid ComputeBudget InstructionType's\n * @internal\n */\nexport const COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in ComputeBudgetInstructionType]: InstructionType<\n ComputeBudgetInstructionInputData[Instruction]\n >;\n}>({\n RequestUnits: {\n index: 0,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['RequestUnits']\n >([\n BufferLayout.u8('instruction'),\n BufferLayout.u32('units'),\n BufferLayout.u32('additionalFee'),\n ]),\n },\n RequestHeapFrame: {\n index: 1,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['RequestHeapFrame']\n >([BufferLayout.u8('instruction'), BufferLayout.u32('bytes')]),\n },\n SetComputeUnitLimit: {\n index: 2,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['SetComputeUnitLimit']\n >([BufferLayout.u8('instruction'), BufferLayout.u32('units')]),\n },\n SetComputeUnitPrice: {\n index: 3,\n layout: BufferLayout.struct<\n ComputeBudgetInstructionInputData['SetComputeUnitPrice']\n >([BufferLayout.u8('instruction'), u64('microLamports')]),\n },\n});\n\n/**\n * Factory class for transaction instructions to interact with the Compute Budget program\n */\nexport class ComputeBudgetProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Compute Budget program\n */\n static programId: PublicKey = new PublicKey(\n 'ComputeBudget111111111111111111111111111111',\n );\n\n /**\n * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice}\n */\n static requestUnits(params: RequestUnitsParams): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n\n static requestHeapFrame(\n params: RequestHeapFrameParams,\n ): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n\n static setComputeUnitLimit(\n params: SetComputeUnitLimitParams,\n ): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit;\n const data = encodeData(type, params);\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n\n static setComputeUnitPrice(\n params: SetComputeUnitPriceParams,\n ): TransactionInstruction {\n const type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice;\n const data = encodeData(type, {\n microLamports: BigInt(params.microLamports),\n });\n return new TransactionInstruction({\n keys: [],\n programId: this.programId,\n data,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\n\nimport {Keypair} from '../keypair';\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {sign} from '../utils/ed25519';\n\nconst PRIVATE_KEY_BYTES = 64;\nconst PUBLIC_KEY_BYTES = 32;\nconst SIGNATURE_BYTES = 64;\n\n/**\n * Params for creating an ed25519 instruction using a public key\n */\nexport type CreateEd25519InstructionWithPublicKeyParams = {\n publicKey: Uint8Array;\n message: Uint8Array;\n signature: Uint8Array;\n instructionIndex?: number;\n};\n\n/**\n * Params for creating an ed25519 instruction using a private key\n */\nexport type CreateEd25519InstructionWithPrivateKeyParams = {\n privateKey: Uint8Array;\n message: Uint8Array;\n instructionIndex?: number;\n};\n\nconst ED25519_INSTRUCTION_LAYOUT = BufferLayout.struct<\n Readonly<{\n messageDataOffset: number;\n messageDataSize: number;\n messageInstructionIndex: number;\n numSignatures: number;\n padding: number;\n publicKeyInstructionIndex: number;\n publicKeyOffset: number;\n signatureInstructionIndex: number;\n signatureOffset: number;\n }>\n>([\n BufferLayout.u8('numSignatures'),\n BufferLayout.u8('padding'),\n BufferLayout.u16('signatureOffset'),\n BufferLayout.u16('signatureInstructionIndex'),\n BufferLayout.u16('publicKeyOffset'),\n BufferLayout.u16('publicKeyInstructionIndex'),\n BufferLayout.u16('messageDataOffset'),\n BufferLayout.u16('messageDataSize'),\n BufferLayout.u16('messageInstructionIndex'),\n]);\n\nexport class Ed25519Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the ed25519 program\n */\n static programId: PublicKey = new PublicKey(\n 'Ed25519SigVerify111111111111111111111111111',\n );\n\n /**\n * Create an ed25519 instruction with a public key and signature. The\n * public key must be a buffer that is 32 bytes long, and the signature\n * must be a buffer of 64 bytes.\n */\n static createInstructionWithPublicKey(\n params: CreateEd25519InstructionWithPublicKeyParams,\n ): TransactionInstruction {\n const {publicKey, message, signature, instructionIndex} = params;\n\n assert(\n publicKey.length === PUBLIC_KEY_BYTES,\n `Public Key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`,\n );\n\n assert(\n signature.length === SIGNATURE_BYTES,\n `Signature must be ${SIGNATURE_BYTES} bytes but received ${signature.length} bytes`,\n );\n\n const publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span;\n const signatureOffset = publicKeyOffset + publicKey.length;\n const messageDataOffset = signatureOffset + signature.length;\n const numSignatures = 1;\n\n const instructionData = Buffer.alloc(messageDataOffset + message.length);\n\n const index =\n instructionIndex == null\n ? 0xffff // An index of `u16::MAX` makes it default to the current instruction.\n : instructionIndex;\n\n ED25519_INSTRUCTION_LAYOUT.encode(\n {\n numSignatures,\n padding: 0,\n signatureOffset,\n signatureInstructionIndex: index,\n publicKeyOffset,\n publicKeyInstructionIndex: index,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: index,\n },\n instructionData,\n );\n\n instructionData.fill(publicKey, publicKeyOffset);\n instructionData.fill(signature, signatureOffset);\n instructionData.fill(message, messageDataOffset);\n\n return new TransactionInstruction({\n keys: [],\n programId: Ed25519Program.programId,\n data: instructionData,\n });\n }\n\n /**\n * Create an ed25519 instruction with a private key. The private key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPrivateKey(\n params: CreateEd25519InstructionWithPrivateKeyParams,\n ): TransactionInstruction {\n const {privateKey, message, instructionIndex} = params;\n\n assert(\n privateKey.length === PRIVATE_KEY_BYTES,\n `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${privateKey.length} bytes`,\n );\n\n try {\n const keypair = Keypair.fromSecretKey(privateKey);\n const publicKey = keypair.publicKey.toBytes();\n const signature = sign(message, keypair.secretKey);\n\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n instructionIndex,\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\n","import {secp256k1} from '@noble/curves/secp256k1';\n\nexport const ecdsaSign = (\n msgHash: Parameters[0],\n privKey: Parameters[1],\n) => {\n const signature = secp256k1.sign(msgHash, privKey);\n return [signature.toCompactRawBytes(), signature.recovery!] as const;\n};\nexport const isValidPrivateKey = secp256k1.utils.isValidPrivateKey;\nexport const publicKeyCreate = secp256k1.getPublicKey;\n","import {Buffer} from 'buffer';\nimport * as BufferLayout from '@solana/buffer-layout';\nimport {keccak_256} from '@noble/hashes/sha3';\n\nimport {PublicKey} from '../publickey';\nimport {TransactionInstruction} from '../transaction';\nimport assert from '../utils/assert';\nimport {publicKeyCreate, ecdsaSign} from '../utils/secp256k1';\nimport {toBuffer} from '../utils/to-buffer';\n\nconst PRIVATE_KEY_BYTES = 32;\nconst ETHEREUM_ADDRESS_BYTES = 20;\nconst PUBLIC_KEY_BYTES = 64;\nconst SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11;\n\n/**\n * Params for creating an secp256k1 instruction using a public key\n */\nexport type CreateSecp256k1InstructionWithPublicKeyParams = {\n publicKey: Buffer | Uint8Array | Array;\n message: Buffer | Uint8Array | Array;\n signature: Buffer | Uint8Array | Array;\n recoveryId: number;\n instructionIndex?: number;\n};\n\n/**\n * Params for creating an secp256k1 instruction using an Ethereum address\n */\nexport type CreateSecp256k1InstructionWithEthAddressParams = {\n ethAddress: Buffer | Uint8Array | Array | string;\n message: Buffer | Uint8Array | Array;\n signature: Buffer | Uint8Array | Array;\n recoveryId: number;\n instructionIndex?: number;\n};\n\n/**\n * Params for creating an secp256k1 instruction using a private key\n */\nexport type CreateSecp256k1InstructionWithPrivateKeyParams = {\n privateKey: Buffer | Uint8Array | Array;\n message: Buffer | Uint8Array | Array;\n instructionIndex?: number;\n};\n\nconst SECP256K1_INSTRUCTION_LAYOUT = BufferLayout.struct<\n Readonly<{\n ethAddress: Uint8Array;\n ethAddressInstructionIndex: number;\n ethAddressOffset: number;\n messageDataOffset: number;\n messageDataSize: number;\n messageInstructionIndex: number;\n numSignatures: number;\n recoveryId: number;\n signature: Uint8Array;\n signatureInstructionIndex: number;\n signatureOffset: number;\n }>\n>([\n BufferLayout.u8('numSignatures'),\n BufferLayout.u16('signatureOffset'),\n BufferLayout.u8('signatureInstructionIndex'),\n BufferLayout.u16('ethAddressOffset'),\n BufferLayout.u8('ethAddressInstructionIndex'),\n BufferLayout.u16('messageDataOffset'),\n BufferLayout.u16('messageDataSize'),\n BufferLayout.u8('messageInstructionIndex'),\n BufferLayout.blob(20, 'ethAddress'),\n BufferLayout.blob(64, 'signature'),\n BufferLayout.u8('recoveryId'),\n]);\n\nexport class Secp256k1Program {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the secp256k1 program\n */\n static programId: PublicKey = new PublicKey(\n 'KeccakSecp256k11111111111111111111111111111',\n );\n\n /**\n * Construct an Ethereum address from a secp256k1 public key buffer.\n * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer\n */\n static publicKeyToEthAddress(\n publicKey: Buffer | Uint8Array | Array,\n ): Buffer {\n assert(\n publicKey.length === PUBLIC_KEY_BYTES,\n `Public key must be ${PUBLIC_KEY_BYTES} bytes but received ${publicKey.length} bytes`,\n );\n\n try {\n return Buffer.from(keccak_256(toBuffer(publicKey))).slice(\n -ETHEREUM_ADDRESS_BYTES,\n );\n } catch (error) {\n throw new Error(`Error constructing Ethereum address: ${error}`);\n }\n }\n\n /**\n * Create an secp256k1 instruction with a public key. The public key\n * must be a buffer that is 64 bytes long.\n */\n static createInstructionWithPublicKey(\n params: CreateSecp256k1InstructionWithPublicKeyParams,\n ): TransactionInstruction {\n const {publicKey, message, signature, recoveryId, instructionIndex} =\n params;\n return Secp256k1Program.createInstructionWithEthAddress({\n ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey),\n message,\n signature,\n recoveryId,\n instructionIndex,\n });\n }\n\n /**\n * Create an secp256k1 instruction with an Ethereum address. The address\n * must be a hex string or a buffer that is 20 bytes long.\n */\n static createInstructionWithEthAddress(\n params: CreateSecp256k1InstructionWithEthAddressParams,\n ): TransactionInstruction {\n const {\n ethAddress: rawAddress,\n message,\n signature,\n recoveryId,\n instructionIndex = 0,\n } = params;\n\n let ethAddress;\n if (typeof rawAddress === 'string') {\n if (rawAddress.startsWith('0x')) {\n ethAddress = Buffer.from(rawAddress.substr(2), 'hex');\n } else {\n ethAddress = Buffer.from(rawAddress, 'hex');\n }\n } else {\n ethAddress = rawAddress;\n }\n\n assert(\n ethAddress.length === ETHEREUM_ADDRESS_BYTES,\n `Address must be ${ETHEREUM_ADDRESS_BYTES} bytes but received ${ethAddress.length} bytes`,\n );\n\n const dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE;\n const ethAddressOffset = dataStart;\n const signatureOffset = dataStart + ethAddress.length;\n const messageDataOffset = signatureOffset + signature.length + 1;\n const numSignatures = 1;\n\n const instructionData = Buffer.alloc(\n SECP256K1_INSTRUCTION_LAYOUT.span + message.length,\n );\n\n SECP256K1_INSTRUCTION_LAYOUT.encode(\n {\n numSignatures,\n signatureOffset,\n signatureInstructionIndex: instructionIndex,\n ethAddressOffset,\n ethAddressInstructionIndex: instructionIndex,\n messageDataOffset,\n messageDataSize: message.length,\n messageInstructionIndex: instructionIndex,\n signature: toBuffer(signature),\n ethAddress: toBuffer(ethAddress),\n recoveryId,\n },\n instructionData,\n );\n\n instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span);\n\n return new TransactionInstruction({\n keys: [],\n programId: Secp256k1Program.programId,\n data: instructionData,\n });\n }\n\n /**\n * Create an secp256k1 instruction with a private key. The private key\n * must be a buffer that is 32 bytes long.\n */\n static createInstructionWithPrivateKey(\n params: CreateSecp256k1InstructionWithPrivateKeyParams,\n ): TransactionInstruction {\n const {privateKey: pkey, message, instructionIndex} = params;\n\n assert(\n pkey.length === PRIVATE_KEY_BYTES,\n `Private key must be ${PRIVATE_KEY_BYTES} bytes but received ${pkey.length} bytes`,\n );\n\n try {\n const privateKey = toBuffer(pkey);\n const publicKey = publicKeyCreate(\n privateKey,\n false /* isCompressed */,\n ).slice(1); // throw away leading byte\n const messageHash = Buffer.from(keccak_256(toBuffer(message)));\n const [signature, recoveryId] = ecdsaSign(messageHash, privateKey);\n\n return this.createInstructionWithPublicKey({\n publicKey,\n message,\n signature,\n recoveryId,\n instructionIndex,\n });\n } catch (error) {\n throw new Error(`Error creating instruction; ${error}`);\n }\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {PublicKey} from '../publickey';\nimport {SystemProgram} from './system';\nimport {\n SYSVAR_CLOCK_PUBKEY,\n SYSVAR_RENT_PUBKEY,\n SYSVAR_STAKE_HISTORY_PUBKEY,\n} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\n\n/**\n * Address of the stake config account which configures the rate\n * of stake warmup and cooldown as well as the slashing penalty.\n */\nexport const STAKE_CONFIG_ID = new PublicKey(\n 'StakeConfig11111111111111111111111111111111',\n);\n\n/**\n * Stake account authority info\n */\nexport class Authorized {\n /** stake authority */\n staker: PublicKey;\n /** withdraw authority */\n withdrawer: PublicKey;\n\n /**\n * Create a new Authorized object\n * @param staker the stake authority\n * @param withdrawer the withdraw authority\n */\n constructor(staker: PublicKey, withdrawer: PublicKey) {\n this.staker = staker;\n this.withdrawer = withdrawer;\n }\n}\n\ntype AuthorizedRaw = Readonly<{\n staker: Uint8Array;\n withdrawer: Uint8Array;\n}>;\n\n/**\n * Stake account lockup info\n */\nexport class Lockup {\n /** Unix timestamp of lockup expiration */\n unixTimestamp: number;\n /** Epoch of lockup expiration */\n epoch: number;\n /** Lockup custodian authority */\n custodian: PublicKey;\n\n /**\n * Create a new Lockup object\n */\n constructor(unixTimestamp: number, epoch: number, custodian: PublicKey) {\n this.unixTimestamp = unixTimestamp;\n this.epoch = epoch;\n this.custodian = custodian;\n }\n\n /**\n * Default, inactive Lockup value\n */\n static default: Lockup = new Lockup(0, 0, PublicKey.default);\n}\n\ntype LockupRaw = Readonly<{\n custodian: Uint8Array;\n epoch: number;\n unixTimestamp: number;\n}>;\n\n/**\n * Create stake account transaction params\n */\nexport type CreateStakeAccountParams = {\n /** Address of the account which will fund creation */\n fromPubkey: PublicKey;\n /** Address of the new stake account */\n stakePubkey: PublicKey;\n /** Authorities of the new stake account */\n authorized: Authorized;\n /** Lockup of the new stake account */\n lockup?: Lockup;\n /** Funding amount */\n lamports: number;\n};\n\n/**\n * Create stake account with seed transaction params\n */\nexport type CreateStakeAccountWithSeedParams = {\n fromPubkey: PublicKey;\n stakePubkey: PublicKey;\n basePubkey: PublicKey;\n seed: string;\n authorized: Authorized;\n lockup?: Lockup;\n lamports: number;\n};\n\n/**\n * Initialize stake instruction params\n */\nexport type InitializeStakeParams = {\n stakePubkey: PublicKey;\n authorized: Authorized;\n lockup?: Lockup;\n};\n\n/**\n * Delegate stake instruction params\n */\nexport type DelegateStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n votePubkey: PublicKey;\n};\n\n/**\n * Authorize stake instruction params\n */\nexport type AuthorizeStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n newAuthorizedPubkey: PublicKey;\n stakeAuthorizationType: StakeAuthorizationType;\n custodianPubkey?: PublicKey;\n};\n\n/**\n * Authorize stake instruction params using a derived key\n */\nexport type AuthorizeWithSeedStakeParams = {\n stakePubkey: PublicKey;\n authorityBase: PublicKey;\n authoritySeed: string;\n authorityOwner: PublicKey;\n newAuthorizedPubkey: PublicKey;\n stakeAuthorizationType: StakeAuthorizationType;\n custodianPubkey?: PublicKey;\n};\n\n/**\n * Split stake instruction params\n */\nexport type SplitStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n splitStakePubkey: PublicKey;\n lamports: number;\n};\n\n/**\n * Split with seed transaction params\n */\nexport type SplitStakeWithSeedParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n splitStakePubkey: PublicKey;\n basePubkey: PublicKey;\n seed: string;\n lamports: number;\n};\n\n/**\n * Withdraw stake instruction params\n */\nexport type WithdrawStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n toPubkey: PublicKey;\n lamports: number;\n custodianPubkey?: PublicKey;\n};\n\n/**\n * Deactivate stake instruction params\n */\nexport type DeactivateStakeParams = {\n stakePubkey: PublicKey;\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Merge stake instruction params\n */\nexport type MergeStakeParams = {\n stakePubkey: PublicKey;\n sourceStakePubKey: PublicKey;\n authorizedPubkey: PublicKey;\n};\n\n/**\n * Stake Instruction class\n */\nexport class StakeInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a stake instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): StakeInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: StakeInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(STAKE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType as StakeInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error('Instruction type incorrect; not a StakeInstruction');\n }\n\n return type;\n }\n\n /**\n * Decode a initialize stake instruction and retrieve the instruction params.\n */\n static decodeInitialize(\n instruction: TransactionInstruction,\n ): InitializeStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {authorized, lockup} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Initialize,\n instruction.data,\n );\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorized: new Authorized(\n new PublicKey(authorized.staker),\n new PublicKey(authorized.withdrawer),\n ),\n lockup: new Lockup(\n lockup.unixTimestamp,\n lockup.epoch,\n new PublicKey(lockup.custodian),\n ),\n };\n }\n\n /**\n * Decode a delegate stake instruction and retrieve the instruction params.\n */\n static decodeDelegate(\n instruction: TransactionInstruction,\n ): DelegateStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 6);\n decodeData(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data);\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n votePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[5].pubkey,\n };\n }\n\n /**\n * Decode an authorize stake instruction and retrieve the instruction params.\n */\n static decodeAuthorize(\n instruction: TransactionInstruction,\n ): AuthorizeStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {newAuthorized, stakeAuthorizationType} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Authorize,\n instruction.data,\n );\n\n const o: AuthorizeStakeParams = {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType,\n },\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode an authorize-with-seed stake instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(\n instruction: TransactionInstruction,\n ): AuthorizeWithSeedStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 2);\n\n const {\n newAuthorized,\n stakeAuthorizationType,\n authoritySeed,\n authorityOwner,\n } = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,\n instruction.data,\n );\n\n const o: AuthorizeWithSeedStakeParams = {\n stakePubkey: instruction.keys[0].pubkey,\n authorityBase: instruction.keys[1].pubkey,\n authoritySeed: authoritySeed,\n authorityOwner: new PublicKey(authorityOwner),\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n stakeAuthorizationType: {\n index: stakeAuthorizationType,\n },\n };\n if (instruction.keys.length > 3) {\n o.custodianPubkey = instruction.keys[3].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a split stake instruction and retrieve the instruction params.\n */\n static decodeSplit(instruction: TransactionInstruction): SplitStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n const {lamports} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Split,\n instruction.data,\n );\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n splitStakePubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n lamports,\n };\n }\n\n /**\n * Decode a merge stake instruction and retrieve the instruction params.\n */\n static decodeMerge(instruction: TransactionInstruction): MergeStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data);\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n sourceStakePubKey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n };\n }\n\n /**\n * Decode a withdraw stake instruction and retrieve the instruction params.\n */\n static decodeWithdraw(\n instruction: TransactionInstruction,\n ): WithdrawStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 5);\n const {lamports} = decodeData(\n STAKE_INSTRUCTION_LAYOUTS.Withdraw,\n instruction.data,\n );\n\n const o: WithdrawStakeParams = {\n stakePubkey: instruction.keys[0].pubkey,\n toPubkey: instruction.keys[1].pubkey,\n authorizedPubkey: instruction.keys[4].pubkey,\n lamports,\n };\n if (instruction.keys.length > 5) {\n o.custodianPubkey = instruction.keys[5].pubkey;\n }\n return o;\n }\n\n /**\n * Decode a deactivate stake instruction and retrieve the instruction params.\n */\n static decodeDeactivate(\n instruction: TransactionInstruction,\n ): DeactivateStakeParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n decodeData(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data);\n\n return {\n stakePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(StakeProgram.programId)) {\n throw new Error('invalid instruction; programId is not StakeProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\n/**\n * An enumeration of valid StakeInstructionType's\n */\nexport type StakeInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof StakeInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'Authorize'\n | 'AuthorizeWithSeed'\n | 'Deactivate'\n | 'Delegate'\n | 'Initialize'\n | 'Merge'\n | 'Split'\n | 'Withdraw';\n\ntype StakeInstructionInputData = {\n Authorize: IInstructionInputData &\n Readonly<{\n newAuthorized: Uint8Array;\n stakeAuthorizationType: number;\n }>;\n AuthorizeWithSeed: IInstructionInputData &\n Readonly<{\n authorityOwner: Uint8Array;\n authoritySeed: string;\n instruction: number;\n newAuthorized: Uint8Array;\n stakeAuthorizationType: number;\n }>;\n Deactivate: IInstructionInputData;\n Delegate: IInstructionInputData;\n Initialize: IInstructionInputData &\n Readonly<{\n authorized: AuthorizedRaw;\n lockup: LockupRaw;\n }>;\n Merge: IInstructionInputData;\n Split: IInstructionInputData &\n Readonly<{\n lamports: number;\n }>;\n Withdraw: IInstructionInputData &\n Readonly<{\n lamports: number;\n }>;\n};\n\n/**\n * An enumeration of valid stake InstructionType's\n * @internal\n */\nexport const STAKE_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in StakeInstructionType]: InstructionType<\n StakeInstructionInputData[Instruction]\n >;\n}>({\n Initialize: {\n index: 0,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.authorized(),\n Layout.lockup(),\n ]),\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('newAuthorized'),\n BufferLayout.u32('stakeAuthorizationType'),\n ]),\n },\n Delegate: {\n index: 2,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]),\n },\n Split: {\n index: 3,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n ]),\n },\n Withdraw: {\n index: 4,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n ]),\n },\n Deactivate: {\n index: 5,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]),\n },\n Merge: {\n index: 7,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n ]),\n },\n AuthorizeWithSeed: {\n index: 8,\n layout: BufferLayout.struct(\n [\n BufferLayout.u32('instruction'),\n Layout.publicKey('newAuthorized'),\n BufferLayout.u32('stakeAuthorizationType'),\n Layout.rustString('authoritySeed'),\n Layout.publicKey('authorityOwner'),\n ],\n ),\n },\n});\n\n/**\n * Stake authorization type\n */\nexport type StakeAuthorizationType = {\n /** The Stake Authorization index (from solana-stake-program) */\n index: number;\n};\n\n/**\n * An enumeration of valid StakeAuthorizationLayout's\n */\nexport const StakeAuthorizationLayout = Object.freeze({\n Staker: {\n index: 0,\n },\n Withdrawer: {\n index: 1,\n },\n});\n\n/**\n * Factory class for transactions to interact with the Stake program\n */\nexport class StakeProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Stake program\n */\n static programId: PublicKey = new PublicKey(\n 'Stake11111111111111111111111111111111111111',\n );\n\n /**\n * Max space of a Stake account\n *\n * This is generated from the solana-stake-program StakeState struct as\n * `StakeStateV2::size_of()`:\n * https://docs.rs/solana-stake-program/latest/solana_stake_program/stake_state/enum.StakeStateV2.html\n */\n static space: number = 200;\n\n /**\n * Generate an Initialize instruction to add to a Stake Create transaction\n */\n static initialize(params: InitializeStakeParams): TransactionInstruction {\n const {stakePubkey, authorized, lockup: maybeLockup} = params;\n const lockup: Lockup = maybeLockup || Lockup.default;\n const type = STAKE_INSTRUCTION_LAYOUTS.Initialize;\n const data = encodeData(type, {\n authorized: {\n staker: toBuffer(authorized.staker.toBuffer()),\n withdrawer: toBuffer(authorized.withdrawer.toBuffer()),\n },\n lockup: {\n unixTimestamp: lockup.unixTimestamp,\n epoch: lockup.epoch,\n custodian: toBuffer(lockup.custodian.toBuffer()),\n },\n });\n const instructionData = {\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a Transaction that creates a new Stake account at\n * an address generated with `from`, a seed, and the Stake programId\n */\n static createAccountWithSeed(\n params: CreateStakeAccountWithSeedParams,\n ): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccountWithSeed({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n basePubkey: params.basePubkey,\n seed: params.seed,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId,\n }),\n );\n\n const {stakePubkey, authorized, lockup} = params;\n return transaction.add(this.initialize({stakePubkey, authorized, lockup}));\n }\n\n /**\n * Generate a Transaction that creates a new Stake account\n */\n static createAccount(params: CreateStakeAccountParams): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.stakePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId,\n }),\n );\n\n const {stakePubkey, authorized, lockup} = params;\n return transaction.add(this.initialize({stakePubkey, authorized, lockup}));\n }\n\n /**\n * Generate a Transaction that delegates Stake tokens to a validator\n * Vote PublicKey. This transaction can also be used to redelegate Stake\n * to a new validator Vote PublicKey.\n */\n static delegate(params: DelegateStakeParams): Transaction {\n const {stakePubkey, authorizedPubkey, votePubkey} = params;\n\n const type = STAKE_INSTRUCTION_LAYOUTS.Delegate;\n const data = encodeData(type);\n\n return new Transaction().add({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: votePubkey, isSigner: false, isWritable: false},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: STAKE_CONFIG_ID, isSigner: false, isWritable: false},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorize(params: AuthorizeStakeParams): Transaction {\n const {\n stakePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey,\n } = params;\n\n const type = STAKE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index,\n });\n\n const keys = [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: true},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false,\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that authorizes a new PublicKey as Staker\n * or Withdrawer on the Stake account.\n */\n static authorizeWithSeed(params: AuthorizeWithSeedStakeParams): Transaction {\n const {\n stakePubkey,\n authorityBase,\n authoritySeed,\n authorityOwner,\n newAuthorizedPubkey,\n stakeAuthorizationType,\n custodianPubkey,\n } = params;\n\n const type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n stakeAuthorizationType: stakeAuthorizationType.index,\n authoritySeed: authoritySeed,\n authorityOwner: toBuffer(authorityOwner.toBuffer()),\n });\n\n const keys = [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: authorityBase, isSigner: true, isWritable: false},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n ];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false,\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * @internal\n */\n static splitInstruction(params: SplitStakeParams): TransactionInstruction {\n const {stakePubkey, authorizedPubkey, splitStakePubkey, lamports} = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Split;\n const data = encodeData(type, {lamports});\n return new TransactionInstruction({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: splitStakePubkey, isSigner: false, isWritable: true},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another stake account\n */\n static split(\n params: SplitStakeParams,\n // Compute the cost of allocating the new stake account in lamports\n rentExemptReserve: number,\n ): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.authorizedPubkey,\n newAccountPubkey: params.splitStakePubkey,\n lamports: rentExemptReserve,\n space: this.space,\n programId: this.programId,\n }),\n );\n return transaction.add(this.splitInstruction(params));\n }\n\n /**\n * Generate a Transaction that splits Stake tokens into another account\n * derived from a base public key and seed\n */\n static splitWithSeed(\n params: SplitStakeWithSeedParams,\n // If this stake account is new, compute the cost of allocating it in lamports\n rentExemptReserve?: number,\n ): Transaction {\n const {\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n basePubkey,\n seed,\n lamports,\n } = params;\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.allocate({\n accountPubkey: splitStakePubkey,\n basePubkey,\n seed,\n space: this.space,\n programId: this.programId,\n }),\n );\n if (rentExemptReserve && rentExemptReserve > 0) {\n transaction.add(\n SystemProgram.transfer({\n fromPubkey: params.authorizedPubkey,\n toPubkey: splitStakePubkey,\n lamports: rentExemptReserve,\n }),\n );\n }\n return transaction.add(\n this.splitInstruction({\n stakePubkey,\n authorizedPubkey,\n splitStakePubkey,\n lamports,\n }),\n );\n }\n\n /**\n * Generate a Transaction that merges Stake accounts.\n */\n static merge(params: MergeStakeParams): Transaction {\n const {stakePubkey, sourceStakePubKey, authorizedPubkey} = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Merge;\n const data = encodeData(type);\n\n return new Transaction().add({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: sourceStakePubKey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that withdraws deactivated Stake tokens.\n */\n static withdraw(params: WithdrawStakeParams): Transaction {\n const {stakePubkey, authorizedPubkey, toPubkey, lamports, custodianPubkey} =\n params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {lamports});\n\n const keys = [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: toPubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: SYSVAR_STAKE_HISTORY_PUBKEY,\n isSigner: false,\n isWritable: false,\n },\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ];\n if (custodianPubkey) {\n keys.push({\n pubkey: custodianPubkey,\n isSigner: true,\n isWritable: false,\n });\n }\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a Transaction that deactivates Stake tokens.\n */\n static deactivate(params: DeactivateStakeParams): Transaction {\n const {stakePubkey, authorizedPubkey} = params;\n const type = STAKE_INSTRUCTION_LAYOUTS.Deactivate;\n const data = encodeData(type);\n\n return new Transaction().add({\n keys: [\n {pubkey: stakePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n });\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\n\nimport {\n encodeData,\n decodeData,\n InstructionType,\n IInstructionInputData,\n} from '../instruction';\nimport * as Layout from '../layout';\nimport {PublicKey} from '../publickey';\nimport {SystemProgram} from './system';\nimport {SYSVAR_CLOCK_PUBKEY, SYSVAR_RENT_PUBKEY} from '../sysvar';\nimport {Transaction, TransactionInstruction} from '../transaction';\nimport {toBuffer} from '../utils/to-buffer';\n\n/**\n * Vote account info\n */\nexport class VoteInit {\n nodePubkey: PublicKey;\n authorizedVoter: PublicKey;\n authorizedWithdrawer: PublicKey;\n commission: number; /** [0, 100] */\n\n constructor(\n nodePubkey: PublicKey,\n authorizedVoter: PublicKey,\n authorizedWithdrawer: PublicKey,\n commission: number,\n ) {\n this.nodePubkey = nodePubkey;\n this.authorizedVoter = authorizedVoter;\n this.authorizedWithdrawer = authorizedWithdrawer;\n this.commission = commission;\n }\n}\n\n/**\n * Create vote account transaction params\n */\nexport type CreateVoteAccountParams = {\n fromPubkey: PublicKey;\n votePubkey: PublicKey;\n voteInit: VoteInit;\n lamports: number;\n};\n\n/**\n * InitializeAccount instruction params\n */\nexport type InitializeAccountParams = {\n votePubkey: PublicKey;\n nodePubkey: PublicKey;\n voteInit: VoteInit;\n};\n\n/**\n * Authorize instruction params\n */\nexport type AuthorizeVoteParams = {\n votePubkey: PublicKey;\n /** Current vote or withdraw authority, depending on `voteAuthorizationType` */\n authorizedPubkey: PublicKey;\n newAuthorizedPubkey: PublicKey;\n voteAuthorizationType: VoteAuthorizationType;\n};\n\n/**\n * AuthorizeWithSeed instruction params\n */\nexport type AuthorizeVoteWithSeedParams = {\n currentAuthorityDerivedKeyBasePubkey: PublicKey;\n currentAuthorityDerivedKeyOwnerPubkey: PublicKey;\n currentAuthorityDerivedKeySeed: string;\n newAuthorizedPubkey: PublicKey;\n voteAuthorizationType: VoteAuthorizationType;\n votePubkey: PublicKey;\n};\n\n/**\n * Withdraw from vote account transaction params\n */\nexport type WithdrawFromVoteAccountParams = {\n votePubkey: PublicKey;\n authorizedWithdrawerPubkey: PublicKey;\n lamports: number;\n toPubkey: PublicKey;\n};\n\n/**\n * Update validator identity (node pubkey) vote account instruction params.\n */\nexport type UpdateValidatorIdentityParams = {\n votePubkey: PublicKey;\n authorizedWithdrawerPubkey: PublicKey;\n nodePubkey: PublicKey;\n};\n\n/**\n * Vote Instruction class\n */\nexport class VoteInstruction {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Decode a vote instruction and retrieve the instruction type.\n */\n static decodeInstructionType(\n instruction: TransactionInstruction,\n ): VoteInstructionType {\n this.checkProgramId(instruction.programId);\n\n const instructionTypeLayout = BufferLayout.u32('instruction');\n const typeIndex = instructionTypeLayout.decode(instruction.data);\n\n let type: VoteInstructionType | undefined;\n for (const [ixType, layout] of Object.entries(VOTE_INSTRUCTION_LAYOUTS)) {\n if (layout.index == typeIndex) {\n type = ixType as VoteInstructionType;\n break;\n }\n }\n\n if (!type) {\n throw new Error('Instruction type incorrect; not a VoteInstruction');\n }\n\n return type;\n }\n\n /**\n * Decode an initialize vote instruction and retrieve the instruction params.\n */\n static decodeInitializeAccount(\n instruction: TransactionInstruction,\n ): InitializeAccountParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 4);\n\n const {voteInit} = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.InitializeAccount,\n instruction.data,\n );\n\n return {\n votePubkey: instruction.keys[0].pubkey,\n nodePubkey: instruction.keys[3].pubkey,\n voteInit: new VoteInit(\n new PublicKey(voteInit.nodePubkey),\n new PublicKey(voteInit.authorizedVoter),\n new PublicKey(voteInit.authorizedWithdrawer),\n voteInit.commission,\n ),\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorize(\n instruction: TransactionInstruction,\n ): AuthorizeVoteParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {newAuthorized, voteAuthorizationType} = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.Authorize,\n instruction.data,\n );\n\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedPubkey: instruction.keys[2].pubkey,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType,\n },\n };\n }\n\n /**\n * Decode an authorize instruction and retrieve the instruction params.\n */\n static decodeAuthorizeWithSeed(\n instruction: TransactionInstruction,\n ): AuthorizeVoteWithSeedParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorized,\n voteAuthorizationType,\n },\n } = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed,\n instruction.data,\n );\n\n return {\n currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey,\n currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(\n currentAuthorityDerivedKeyOwnerPubkey,\n ),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey: new PublicKey(newAuthorized),\n voteAuthorizationType: {\n index: voteAuthorizationType,\n },\n votePubkey: instruction.keys[0].pubkey,\n };\n }\n\n /**\n * Decode a withdraw instruction and retrieve the instruction params.\n */\n static decodeWithdraw(\n instruction: TransactionInstruction,\n ): WithdrawFromVoteAccountParams {\n this.checkProgramId(instruction.programId);\n this.checkKeyLength(instruction.keys, 3);\n\n const {lamports} = decodeData(\n VOTE_INSTRUCTION_LAYOUTS.Withdraw,\n instruction.data,\n );\n\n return {\n votePubkey: instruction.keys[0].pubkey,\n authorizedWithdrawerPubkey: instruction.keys[2].pubkey,\n lamports,\n toPubkey: instruction.keys[1].pubkey,\n };\n }\n\n /**\n * @internal\n */\n static checkProgramId(programId: PublicKey) {\n if (!programId.equals(VoteProgram.programId)) {\n throw new Error('invalid instruction; programId is not VoteProgram');\n }\n }\n\n /**\n * @internal\n */\n static checkKeyLength(keys: Array, expectedLength: number) {\n if (keys.length < expectedLength) {\n throw new Error(\n `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,\n );\n }\n }\n}\n\n/**\n * An enumeration of valid VoteInstructionType's\n */\nexport type VoteInstructionType =\n // FIXME\n // It would be preferable for this type to be `keyof VoteInstructionInputData`\n // but Typedoc does not transpile `keyof` expressions.\n // See https://github.com/TypeStrong/typedoc/issues/1894\n | 'Authorize'\n | 'AuthorizeWithSeed'\n | 'InitializeAccount'\n | 'Withdraw'\n | 'UpdateValidatorIdentity';\n\n/** @internal */\nexport type VoteAuthorizeWithSeedArgs = Readonly<{\n currentAuthorityDerivedKeyOwnerPubkey: Uint8Array;\n currentAuthorityDerivedKeySeed: string;\n newAuthorized: Uint8Array;\n voteAuthorizationType: number;\n}>;\ntype VoteInstructionInputData = {\n Authorize: IInstructionInputData & {\n newAuthorized: Uint8Array;\n voteAuthorizationType: number;\n };\n AuthorizeWithSeed: IInstructionInputData & {\n voteAuthorizeWithSeedArgs: VoteAuthorizeWithSeedArgs;\n };\n InitializeAccount: IInstructionInputData & {\n voteInit: Readonly<{\n authorizedVoter: Uint8Array;\n authorizedWithdrawer: Uint8Array;\n commission: number;\n nodePubkey: Uint8Array;\n }>;\n };\n Withdraw: IInstructionInputData & {\n lamports: number;\n };\n UpdateValidatorIdentity: IInstructionInputData;\n};\n\nconst VOTE_INSTRUCTION_LAYOUTS = Object.freeze<{\n [Instruction in VoteInstructionType]: InstructionType<\n VoteInstructionInputData[Instruction]\n >;\n}>({\n InitializeAccount: {\n index: 0,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.voteInit(),\n ]),\n },\n Authorize: {\n index: 1,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.publicKey('newAuthorized'),\n BufferLayout.u32('voteAuthorizationType'),\n ]),\n },\n Withdraw: {\n index: 3,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n BufferLayout.ns64('lamports'),\n ]),\n },\n UpdateValidatorIdentity: {\n index: 4,\n layout: BufferLayout.struct<\n VoteInstructionInputData['UpdateValidatorIdentity']\n >([BufferLayout.u32('instruction')]),\n },\n AuthorizeWithSeed: {\n index: 10,\n layout: BufferLayout.struct([\n BufferLayout.u32('instruction'),\n Layout.voteAuthorizeWithSeedArgs(),\n ]),\n },\n});\n\n/**\n * VoteAuthorize type\n */\nexport type VoteAuthorizationType = {\n /** The VoteAuthorize index (from solana-vote-program) */\n index: number;\n};\n\n/**\n * An enumeration of valid VoteAuthorization layouts.\n */\nexport const VoteAuthorizationLayout = Object.freeze({\n Voter: {\n index: 0,\n },\n Withdrawer: {\n index: 1,\n },\n});\n\n/**\n * Factory class for transactions to interact with the Vote program\n */\nexport class VoteProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the Vote program\n */\n static programId: PublicKey = new PublicKey(\n 'Vote111111111111111111111111111111111111111',\n );\n\n /**\n * Max space of a Vote account\n *\n * This is generated from the solana-vote-program VoteState struct as\n * `VoteState::size_of()`:\n * https://docs.rs/solana-vote-program/1.9.5/solana_vote_program/vote_state/struct.VoteState.html#method.size_of\n *\n * KEEP IN SYNC WITH `VoteState::size_of()` in https://github.com/solana-labs/solana/blob/a474cb24b9238f5edcc982f65c0b37d4a1046f7e/sdk/program/src/vote/state/mod.rs#L340-L342\n */\n static space: number = 3762;\n\n /**\n * Generate an Initialize instruction.\n */\n static initializeAccount(\n params: InitializeAccountParams,\n ): TransactionInstruction {\n const {votePubkey, nodePubkey, voteInit} = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount;\n const data = encodeData(type, {\n voteInit: {\n nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()),\n authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()),\n authorizedWithdrawer: toBuffer(\n voteInit.authorizedWithdrawer.toBuffer(),\n ),\n commission: voteInit.commission,\n },\n });\n const instructionData = {\n keys: [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: nodePubkey, isSigner: true, isWritable: false},\n ],\n programId: this.programId,\n data,\n };\n return new TransactionInstruction(instructionData);\n }\n\n /**\n * Generate a transaction that creates a new Vote account.\n */\n static createAccount(params: CreateVoteAccountParams): Transaction {\n const transaction = new Transaction();\n transaction.add(\n SystemProgram.createAccount({\n fromPubkey: params.fromPubkey,\n newAccountPubkey: params.votePubkey,\n lamports: params.lamports,\n space: this.space,\n programId: this.programId,\n }),\n );\n\n return transaction.add(\n this.initializeAccount({\n votePubkey: params.votePubkey,\n nodePubkey: params.voteInit.nodePubkey,\n voteInit: params.voteInit,\n }),\n );\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account.\n */\n static authorize(params: AuthorizeVoteParams): Transaction {\n const {\n votePubkey,\n authorizedPubkey,\n newAuthorizedPubkey,\n voteAuthorizationType,\n } = params;\n\n const type = VOTE_INSTRUCTION_LAYOUTS.Authorize;\n const data = encodeData(type, {\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index,\n });\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {pubkey: authorizedPubkey, isSigner: true, isWritable: false},\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account\n * where the current Voter or Withdrawer authority is a derived key.\n */\n static authorizeWithSeed(params: AuthorizeVoteWithSeedParams): Transaction {\n const {\n currentAuthorityDerivedKeyBasePubkey,\n currentAuthorityDerivedKeyOwnerPubkey,\n currentAuthorityDerivedKeySeed,\n newAuthorizedPubkey,\n voteAuthorizationType,\n votePubkey,\n } = params;\n\n const type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed;\n const data = encodeData(type, {\n voteAuthorizeWithSeedArgs: {\n currentAuthorityDerivedKeyOwnerPubkey: toBuffer(\n currentAuthorityDerivedKeyOwnerPubkey.toBuffer(),\n ),\n currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed,\n newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()),\n voteAuthorizationType: voteAuthorizationType.index,\n },\n });\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},\n {\n pubkey: currentAuthorityDerivedKeyBasePubkey,\n isSigner: true,\n isWritable: false,\n },\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction to withdraw from a Vote account.\n */\n static withdraw(params: WithdrawFromVoteAccountParams): Transaction {\n const {votePubkey, authorizedWithdrawerPubkey, lamports, toPubkey} = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.Withdraw;\n const data = encodeData(type, {lamports});\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: toPubkey, isSigner: false, isWritable: true},\n {pubkey: authorizedWithdrawerPubkey, isSigner: true, isWritable: false},\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n\n /**\n * Generate a transaction to withdraw safely from a Vote account.\n *\n * This function was created as a safeguard for vote accounts running validators, `safeWithdraw`\n * checks that the withdraw amount will not exceed the specified balance while leaving enough left\n * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the\n * `withdraw` method directly.\n */\n static safeWithdraw(\n params: WithdrawFromVoteAccountParams,\n currentVoteAccountBalance: number,\n rentExemptMinimum: number,\n ): Transaction {\n if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {\n throw new Error(\n 'Withdraw will leave vote account with insufficient funds.',\n );\n }\n return VoteProgram.withdraw(params);\n }\n\n /**\n * Generate a transaction to update the validator identity (node pubkey) of a Vote account.\n */\n static updateValidatorIdentity(\n params: UpdateValidatorIdentityParams,\n ): Transaction {\n const {votePubkey, authorizedWithdrawerPubkey, nodePubkey} = params;\n const type = VOTE_INSTRUCTION_LAYOUTS.UpdateValidatorIdentity;\n const data = encodeData(type);\n\n const keys = [\n {pubkey: votePubkey, isSigner: false, isWritable: true},\n {pubkey: nodePubkey, isSigner: true, isWritable: false},\n {pubkey: authorizedWithdrawerPubkey, isSigner: true, isWritable: false},\n ];\n\n return new Transaction().add({\n keys,\n programId: this.programId,\n data,\n });\n }\n}\n","import {Buffer} from 'buffer';\nimport {\n assert as assertType,\n optional,\n string,\n type as pick,\n} from 'superstruct';\n\nimport * as Layout from './layout';\nimport * as shortvec from './utils/shortvec-encoding';\nimport {PublicKey, PUBLIC_KEY_LENGTH} from './publickey';\nimport {guardedShift, guardedSplice} from './utils/guarded-array-utils';\n\nexport const VALIDATOR_INFO_KEY = new PublicKey(\n 'Va1idator1nfo111111111111111111111111111111',\n);\n\n/**\n * @internal\n */\ntype ConfigKey = {\n publicKey: PublicKey;\n isSigner: boolean;\n};\n\n/**\n * Info used to identity validators.\n */\nexport type Info = {\n /** validator name */\n name: string;\n /** optional, validator website */\n website?: string;\n /** optional, extra information the validator chose to share */\n details?: string;\n /** optional, validator logo URL */\n iconUrl?: string;\n /** optional, used to identify validators on keybase.io */\n keybaseUsername?: string;\n};\n\nconst InfoString = pick({\n name: string(),\n website: optional(string()),\n details: optional(string()),\n iconUrl: optional(string()),\n keybaseUsername: optional(string()),\n});\n\n/**\n * ValidatorInfo class\n */\nexport class ValidatorInfo {\n /**\n * validator public key\n */\n key: PublicKey;\n /**\n * validator information\n */\n info: Info;\n\n /**\n * Construct a valid ValidatorInfo\n *\n * @param key validator public key\n * @param info validator information\n */\n constructor(key: PublicKey, info: Info) {\n this.key = key;\n this.info = info;\n }\n\n /**\n * Deserialize ValidatorInfo from the config account data. Exactly two config\n * keys are required in the data.\n *\n * @param buffer config account data\n * @return null if info was not found\n */\n static fromConfigData(\n buffer: Buffer | Uint8Array | Array,\n ): ValidatorInfo | null {\n let byteArray = [...buffer];\n const configKeyCount = shortvec.decodeLength(byteArray);\n if (configKeyCount !== 2) return null;\n\n const configKeys: Array = [];\n for (let i = 0; i < 2; i++) {\n const publicKey = new PublicKey(\n guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH),\n );\n const isSigner = guardedShift(byteArray) === 1;\n configKeys.push({publicKey, isSigner});\n }\n\n if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {\n if (configKeys[1].isSigner) {\n const rawInfo: any = Layout.rustString().decode(Buffer.from(byteArray));\n const info = JSON.parse(rawInfo as string);\n assertType(info, InfoString);\n return new ValidatorInfo(configKeys[1].publicKey, info);\n }\n }\n\n return null;\n }\n}\n","import * as BufferLayout from '@solana/buffer-layout';\nimport type {Buffer} from 'buffer';\n\nimport * as Layout from './layout';\nimport {PublicKey} from './publickey';\nimport {toBuffer} from './utils/to-buffer';\n\nexport const VOTE_PROGRAM_ID = new PublicKey(\n 'Vote111111111111111111111111111111111111111',\n);\n\nexport type Lockout = {\n slot: number;\n confirmationCount: number;\n};\n\n/**\n * History of how many credits earned by the end of each epoch\n */\nexport type EpochCredits = Readonly<{\n epoch: number;\n credits: number;\n prevCredits: number;\n}>;\n\nexport type AuthorizedVoter = Readonly<{\n epoch: number;\n authorizedVoter: PublicKey;\n}>;\n\ntype AuthorizedVoterRaw = Readonly<{\n authorizedVoter: Uint8Array;\n epoch: number;\n}>;\n\ntype PriorVoters = Readonly<{\n buf: PriorVoterRaw[];\n idx: number;\n isEmpty: number;\n}>;\n\nexport type PriorVoter = Readonly<{\n authorizedPubkey: PublicKey;\n epochOfLastAuthorizedSwitch: number;\n targetEpoch: number;\n}>;\n\ntype PriorVoterRaw = Readonly<{\n authorizedPubkey: Uint8Array;\n epochOfLastAuthorizedSwitch: number;\n targetEpoch: number;\n}>;\n\nexport type BlockTimestamp = Readonly<{\n slot: number;\n timestamp: number;\n}>;\n\ntype VoteAccountData = Readonly<{\n authorizedVoters: AuthorizedVoterRaw[];\n authorizedWithdrawer: Uint8Array;\n commission: number;\n epochCredits: EpochCredits[];\n lastTimestamp: BlockTimestamp;\n nodePubkey: Uint8Array;\n priorVoters: PriorVoters;\n rootSlot: number;\n rootSlotValid: number;\n votes: Lockout[];\n}>;\n\n/**\n * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88\n *\n * @internal\n */\nconst VoteAccountLayout = BufferLayout.struct([\n Layout.publicKey('nodePubkey'),\n Layout.publicKey('authorizedWithdrawer'),\n BufferLayout.u8('commission'),\n BufferLayout.nu64(), // votes.length\n BufferLayout.seq(\n BufferLayout.struct([\n BufferLayout.nu64('slot'),\n BufferLayout.u32('confirmationCount'),\n ]),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'votes',\n ),\n BufferLayout.u8('rootSlotValid'),\n BufferLayout.nu64('rootSlot'),\n BufferLayout.nu64(), // authorizedVoters.length\n BufferLayout.seq(\n BufferLayout.struct([\n BufferLayout.nu64('epoch'),\n Layout.publicKey('authorizedVoter'),\n ]),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'authorizedVoters',\n ),\n BufferLayout.struct(\n [\n BufferLayout.seq(\n BufferLayout.struct([\n Layout.publicKey('authorizedPubkey'),\n BufferLayout.nu64('epochOfLastAuthorizedSwitch'),\n BufferLayout.nu64('targetEpoch'),\n ]),\n 32,\n 'buf',\n ),\n BufferLayout.nu64('idx'),\n BufferLayout.u8('isEmpty'),\n ],\n 'priorVoters',\n ),\n BufferLayout.nu64(), // epochCredits.length\n BufferLayout.seq(\n BufferLayout.struct([\n BufferLayout.nu64('epoch'),\n BufferLayout.nu64('credits'),\n BufferLayout.nu64('prevCredits'),\n ]),\n BufferLayout.offset(BufferLayout.u32(), -8),\n 'epochCredits',\n ),\n BufferLayout.struct(\n [BufferLayout.nu64('slot'), BufferLayout.nu64('timestamp')],\n 'lastTimestamp',\n ),\n]);\n\ntype VoteAccountArgs = {\n nodePubkey: PublicKey;\n authorizedWithdrawer: PublicKey;\n commission: number;\n rootSlot: number | null;\n votes: Lockout[];\n authorizedVoters: AuthorizedVoter[];\n priorVoters: PriorVoter[];\n epochCredits: EpochCredits[];\n lastTimestamp: BlockTimestamp;\n};\n\n/**\n * VoteAccount class\n */\nexport class VoteAccount {\n nodePubkey: PublicKey;\n authorizedWithdrawer: PublicKey;\n commission: number;\n rootSlot: number | null;\n votes: Lockout[];\n authorizedVoters: AuthorizedVoter[];\n priorVoters: PriorVoter[];\n epochCredits: EpochCredits[];\n lastTimestamp: BlockTimestamp;\n\n /**\n * @internal\n */\n constructor(args: VoteAccountArgs) {\n this.nodePubkey = args.nodePubkey;\n this.authorizedWithdrawer = args.authorizedWithdrawer;\n this.commission = args.commission;\n this.rootSlot = args.rootSlot;\n this.votes = args.votes;\n this.authorizedVoters = args.authorizedVoters;\n this.priorVoters = args.priorVoters;\n this.epochCredits = args.epochCredits;\n this.lastTimestamp = args.lastTimestamp;\n }\n\n /**\n * Deserialize VoteAccount from the account data.\n *\n * @param buffer account data\n * @return VoteAccount\n */\n static fromAccountData(\n buffer: Buffer | Uint8Array | Array,\n ): VoteAccount {\n const versionOffset = 4;\n const va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset);\n\n let rootSlot: number | null = va.rootSlot;\n if (!va.rootSlotValid) {\n rootSlot = null;\n }\n\n return new VoteAccount({\n nodePubkey: new PublicKey(va.nodePubkey),\n authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),\n commission: va.commission,\n votes: va.votes,\n rootSlot,\n authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),\n priorVoters: getPriorVoters(va.priorVoters),\n epochCredits: va.epochCredits,\n lastTimestamp: va.lastTimestamp,\n });\n }\n}\n\nfunction parseAuthorizedVoter({\n authorizedVoter,\n epoch,\n}: AuthorizedVoterRaw): AuthorizedVoter {\n return {\n epoch,\n authorizedVoter: new PublicKey(authorizedVoter),\n };\n}\n\nfunction parsePriorVoters({\n authorizedPubkey,\n epochOfLastAuthorizedSwitch,\n targetEpoch,\n}: PriorVoterRaw): PriorVoter {\n return {\n authorizedPubkey: new PublicKey(authorizedPubkey),\n epochOfLastAuthorizedSwitch,\n targetEpoch,\n };\n}\n\nfunction getPriorVoters({buf, idx, isEmpty}: PriorVoters): PriorVoter[] {\n if (isEmpty) {\n return [];\n }\n\n return [\n ...buf.slice(idx + 1).map(parsePriorVoters),\n ...buf.slice(0, idx).map(parsePriorVoters),\n ];\n}\n","const endpoint = {\n http: {\n devnet: 'http://api.devnet.solana.com',\n testnet: 'http://api.testnet.solana.com',\n 'mainnet-beta': 'http://api.mainnet-beta.solana.com/',\n },\n https: {\n devnet: 'https://api.devnet.solana.com',\n testnet: 'https://api.testnet.solana.com',\n 'mainnet-beta': 'https://api.mainnet-beta.solana.com/',\n },\n};\n\nexport type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';\n\n/**\n * Retrieves the RPC API URL for the specified cluster\n * @param {Cluster} [cluster=\"devnet\"] - The cluster name of the RPC API URL to use. Possible options: 'devnet' | 'testnet' | 'mainnet-beta'\n * @param {boolean} [tls=\"http\"] - Use TLS when connecting to cluster.\n *\n * @returns {string} URL string of the RPC endpoint\n */\nexport function clusterApiUrl(cluster?: Cluster, tls?: boolean): string {\n const key = tls === false ? 'http' : 'https';\n\n if (!cluster) {\n return endpoint[key]['devnet'];\n }\n\n const url = endpoint[key][cluster];\n if (!url) {\n throw new Error(`Unknown ${key} cluster: ${cluster}`);\n }\n return url;\n}\n","export * from './account';\nexport * from './blockhash';\nexport * from './bpf-loader-deprecated';\nexport * from './bpf-loader';\nexport * from './connection';\nexport * from './epoch-schedule';\nexport * from './errors';\nexport * from './fee-calculator';\nexport * from './keypair';\nexport * from './loader';\nexport * from './message';\nexport * from './nonce-account';\nexport * from './programs';\nexport * from './publickey';\nexport * from './transaction';\nexport * from './validator-info';\nexport * from './vote-account';\nexport * from './sysvar';\nexport * from './utils';\n\n/**\n * There are 1-billion lamports in one SOL\n */\nexport const LAMPORTS_PER_SOL = 1000000000;\n","import { ChainId, ChainType } from '@lifi/sdk';\nimport { isAddress as isEVMAddress } from 'viem';\nimport { isSVMAddress } from './svm.js';\n\nconst chainTypeAddressValidation = {\n [ChainType.EVM]: isEVMAddress,\n [ChainType.SVM]: isSVMAddress,\n [ChainType.UTXO]: () => false,\n};\n\nexport const getChainTypeFromAddress = (\n address: string,\n): ChainType | undefined => {\n for (const chainType in chainTypeAddressValidation) {\n const isChainType =\n chainTypeAddressValidation[chainType as ChainType](address);\n if (isChainType) {\n return chainType as ChainType;\n }\n }\n};\n\nexport const defaultChainIdsByType = {\n [ChainType.EVM]: ChainId.ETH,\n [ChainType.SVM]: ChainId.SOL,\n [ChainType.UTXO]: ChainId.BTC,\n};\n","import { PublicKey } from '@solana/web3.js';\n\nexport const isSVMAddress = (address: string) => {\n try {\n new PublicKey(address);\n return true;\n } catch {\n return false;\n }\n};\n","import { useEffect, useRef, useState } from 'react';\nimport type { FormFieldNames } from '../stores/form/types.js';\nimport { useFieldValues } from '../stores/form/useFieldValues.js';\n\nexport const useDebouncedWatch = (\n delay: number,\n ...name: T\n) => {\n const watchedValue = useFieldValues(...name);\n const [debouncedValue, setDebouncedValue] = useState(watchedValue);\n const debouncedValueRef = useRef();\n const isMounted = useRef(false);\n\n useEffect(() => {\n if (isMounted.current) {\n const hasWatchedValue = watchedValue.some((value) => value);\n if (hasWatchedValue) {\n const handler = setTimeout(() => {\n setDebouncedValue(watchedValue);\n }, delay);\n return () => clearTimeout(handler);\n }\n debouncedValueRef.current = watchedValue;\n setDebouncedValue(watchedValue);\n return undefined;\n }\n isMounted.current = true;\n return undefined;\n }, [delay, watchedValue]);\n\n return debouncedValue;\n};\n","import { createContext, useContext, useRef } from 'react';\nimport { createWithEqualityFn } from 'zustand/traditional';\nimport type {\n SplitSubvariantProps,\n SplitSubvariantProviderProps,\n SplitSubvariantState,\n SplitSubvariantStore,\n} from './types.js';\n\nexport const SplitSubvariantStoreContext =\n createContext(null);\n\nconst shouldRecreateStore = (\n store: SplitSubvariantStore,\n props: SplitSubvariantProps,\n) => {\n const { state } = store.getState();\n return state !== props.state;\n};\n\nexport function SplitSubvariantStoreProvider({\n children,\n ...props\n}: SplitSubvariantProviderProps) {\n const storeRef = useRef();\n if (!storeRef.current || shouldRecreateStore(storeRef.current, props)) {\n storeRef.current = createSplitSubvariantStore(props);\n }\n return (\n \n {children}\n \n );\n}\n\nexport function useSplitSubvariantStoreContext() {\n const useStore = useContext(SplitSubvariantStoreContext);\n if (!useStore) {\n throw new Error(\n `You forgot to wrap your component in <${SplitSubvariantStoreProvider.name}>.`,\n );\n }\n return useStore;\n}\n\nexport function useSplitSubvariantStore(\n selector: (state: SplitSubvariantState) => T,\n): T {\n const useStore = useSplitSubvariantStoreContext();\n return useStore(selector);\n}\n\nexport const createSplitSubvariantStore = ({ state }: SplitSubvariantProps) =>\n createWithEqualityFn(\n (set) => ({\n state,\n setState(state) {\n set(() => ({\n state,\n }));\n },\n }),\n Object.is,\n );\n","import { useSplitSubvariantStore } from '../stores/settings/useSplitSubvariantStore.js';\n\nexport const useSwapOnly = () => {\n const state = useSplitSubvariantStore((state) => state.state);\n return state === 'swap';\n};\n","import type { Route, RoutesResponse, Token } from '@lifi/sdk';\nimport { LiFiErrorCode, getContractCallsQuote, getRoutes } from '@lifi/sdk';\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\nimport { v4 as uuidv4 } from 'uuid';\nimport { parseUnits } from 'viem';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldValues } from '../stores/form/useFieldValues.js';\nimport { useSetExecutableRoute } from '../stores/routes/useSetExecutableRoute.js';\nimport { useSettings } from '../stores/settings/useSettings.js';\nimport { defaultSlippage } from '../stores/settings/useSettingsStore.js';\nimport { WidgetEvent } from '../types/events.js';\nimport { getChainTypeFromAddress } from '../utils/chainType.js';\nimport { useAccount } from './useAccount.js';\nimport { useChain } from './useChain.js';\nimport { useDebouncedWatch } from './useDebouncedWatch.js';\nimport { useGasRefuel } from './useGasRefuel.js';\nimport { useSwapOnly } from './useSwapOnly.js';\nimport { useToken } from './useToken.js';\nimport { useWidgetEvents } from './useWidgetEvents.js';\n\nconst refetchTime = 60_000;\n\ninterface RoutesProps {\n observableRoute?: Route;\n}\n\nexport const useRoutes = ({ observableRoute }: RoutesProps = {}) => {\n const {\n subvariant,\n sdkConfig,\n contractTool,\n bridges,\n exchanges,\n fee,\n feeConfig,\n } = useWidgetConfig();\n const setExecutableRoute = useSetExecutableRoute();\n const queryClient = useQueryClient();\n const emitter = useWidgetEvents();\n const swapOnly = useSwapOnly();\n const {\n disabledBridges,\n disabledExchanges,\n enabledBridges,\n enabledExchanges,\n enabledAutoRefuel,\n routePriority,\n slippage,\n } = useSettings([\n 'disabledBridges',\n 'disabledExchanges',\n 'enabledBridges',\n 'enabledExchanges',\n 'enabledAutoRefuel',\n 'routePriority',\n 'slippage',\n ]);\n const [fromTokenAmount] = useDebouncedWatch(500, 'fromAmount');\n const [\n fromChainId,\n fromTokenAddress,\n toAddress,\n toTokenAmount,\n toChainId,\n toTokenAddress,\n contractCalls,\n ] = useFieldValues(\n 'fromChain',\n 'fromToken',\n 'toAddress',\n 'toAmount',\n 'toChain',\n 'toToken',\n 'contractCalls',\n );\n const { token: fromToken } = useToken(fromChainId, fromTokenAddress);\n const { token: toToken } = useToken(toChainId, toTokenAddress);\n const { chain: fromChain } = useChain(fromChainId);\n const { chain: toChain } = useChain(toChainId);\n const { enabled: enabledRefuel, fromAmount: gasRecommendationFromAmount } =\n useGasRefuel();\n\n const { account } = useAccount({ chainType: fromChain?.chainType });\n\n const hasAmount = Number(fromTokenAmount) > 0 || Number(toTokenAmount) > 0;\n\n const contractCallQuoteEnabled: boolean =\n subvariant === 'custom' ? Boolean(contractCalls && account.address) : true;\n\n // When we bridge between ecosystems we need to be sure toAddress is set and has the same chainType as toChain\n // If toAddress is set, it must have the same chainType as toChain\n const hasToAddressAndChainTypeSatisfied: boolean =\n !!toChain &&\n !!toAddress &&\n getChainTypeFromAddress(toAddress) === toChain.chainType;\n // We need to check for toAddress only if it is set\n const isToAddressSatisfied = toAddress\n ? hasToAddressAndChainTypeSatisfied\n : true;\n\n // toAddress might be an empty string, but we need to pass undefined if there is no value\n const toWalletAddress = toAddress || undefined;\n\n // We need to send the full allowed tools array if custom tool settings are applied\n const allowedBridges =\n bridges?.allow?.length || bridges?.deny?.length\n ? enabledBridges\n : undefined;\n const allowedExchanges =\n exchanges?.allow?.length || exchanges?.deny?.length\n ? enabledExchanges\n : undefined;\n\n const isEnabled =\n Boolean(Number(fromChainId)) &&\n Boolean(Number(toChainId)) &&\n Boolean(fromToken?.address) &&\n Boolean(toToken?.address) &&\n !Number.isNaN(slippage) &&\n hasAmount &&\n isToAddressSatisfied &&\n contractCallQuoteEnabled;\n\n // Some values should be strictly typed and isEnabled ensures that\n const queryKey = [\n 'routes',\n account.address,\n fromChainId as number,\n fromToken?.address as string,\n fromTokenAmount,\n toWalletAddress,\n toChainId as number,\n toToken?.address as string,\n toTokenAmount,\n contractCalls,\n slippage,\n swapOnly,\n disabledBridges,\n disabledExchanges,\n allowedBridges,\n allowedExchanges,\n routePriority,\n subvariant,\n sdkConfig?.routeOptions?.allowSwitchChain,\n enabledRefuel && enabledAutoRefuel,\n gasRecommendationFromAmount,\n feeConfig?.fee || fee,\n observableRoute?.id,\n ] as const;\n\n const { data, isLoading, isFetching, isFetched, dataUpdatedAt, refetch } =\n useQuery({\n queryKey,\n queryFn: async ({\n queryKey: [\n _,\n fromAddress,\n fromChainId,\n fromTokenAddress,\n fromTokenAmount,\n toAddress,\n toChainId,\n toTokenAddress,\n toTokenAmount,\n contractCalls,\n slippage = defaultSlippage,\n swapOnly,\n disabledBridges,\n disabledExchanges,\n allowedBridges,\n allowedExchanges,\n routePriority,\n subvariant,\n allowSwitchChain,\n enabledRefuel,\n gasRecommendationFromAmount,\n fee,\n observableRouteId,\n ],\n signal,\n }) => {\n const fromAmount = parseUnits(fromTokenAmount, fromToken!.decimals);\n const formattedSlippage = parseFloat(slippage) / 100;\n\n const allowBridges = swapOnly\n ? []\n : observableRoute\n ? observableRoute.steps.flatMap((step) =>\n step.includedSteps.reduce((toolKeys, includedStep) => {\n if (includedStep.type === 'cross') {\n toolKeys.push(includedStep.toolDetails.key);\n }\n return toolKeys;\n }, [] as string[]),\n )\n : allowedBridges;\n const allowExchanges = observableRoute\n ? observableRoute.steps.flatMap((step) =>\n step.includedSteps.reduce((toolKeys, includedStep) => {\n if (includedStep.type === 'swap') {\n toolKeys.push(includedStep.toolDetails.key);\n }\n return toolKeys;\n }, [] as string[]),\n )\n : allowedExchanges;\n\n const calculatedFee = await feeConfig?.calculateFee?.({\n fromChainId,\n toChainId,\n fromTokenAddress,\n toTokenAddress,\n fromAddress,\n toAddress,\n fromAmount,\n slippage: formattedSlippage,\n });\n\n if (subvariant === 'custom' && contractCalls && toTokenAmount) {\n const contractCallQuote = await getContractCallsQuote(\n {\n // Contract calls are enabled only when fromAddress is set\n fromAddress: fromAddress as string,\n fromChain: fromChainId,\n fromToken: fromTokenAddress,\n toAmount: toTokenAmount,\n toChain: toChainId,\n toToken: toTokenAddress,\n contractCalls,\n denyBridges: disabledBridges.length ? disabledBridges : undefined,\n denyExchanges: disabledExchanges.length\n ? disabledExchanges\n : undefined,\n allowBridges,\n allowExchanges,\n toFallbackAddress: toAddress,\n slippage: formattedSlippage,\n fee: calculatedFee || fee,\n },\n { signal },\n );\n\n contractCallQuote.action.toToken = toToken!;\n\n const customStep =\n subvariant === 'custom'\n ? contractCallQuote.includedSteps?.find(\n (step) => step.type === 'custom',\n )\n : undefined;\n\n if (customStep && contractTool) {\n const toolDetails = {\n key: contractTool.name,\n name: contractTool.name,\n logoURI: contractTool.logoURI,\n };\n customStep.toolDetails = toolDetails;\n contractCallQuote.toolDetails = toolDetails;\n }\n\n const route: Route = {\n id: uuidv4(),\n fromChainId: contractCallQuote.action.fromChainId,\n fromAmountUSD: contractCallQuote.estimate.fromAmountUSD || '',\n fromAmount: contractCallQuote.action.fromAmount,\n fromToken: contractCallQuote.action.fromToken,\n fromAddress: contractCallQuote.action.fromAddress,\n toChainId: contractCallQuote.action.toChainId,\n toAmountUSD: contractCallQuote.estimate.toAmountUSD || '',\n toAmount: toTokenAmount,\n toAmountMin: toTokenAmount,\n toToken: toToken!,\n toAddress:\n contractCallQuote.action.toAddress ||\n contractCallQuote.action.fromAddress,\n gasCostUSD: contractCallQuote.estimate.gasCosts?.[0].amountUSD,\n steps: [contractCallQuote],\n insurance: { state: 'NOT_INSURABLE', feeAmountUsd: '0' },\n };\n\n return { routes: [route] } as RoutesResponse;\n }\n\n // Prevent sending a request for the same chain token combinations.\n if (fromChainId === toChainId && fromTokenAddress === toTokenAddress) {\n return;\n }\n\n const data = await getRoutes(\n {\n fromAddress,\n fromAmount: fromAmount.toString(),\n fromChainId,\n fromTokenAddress,\n toAddress,\n toChainId,\n toTokenAddress,\n fromAmountForGas:\n enabledRefuel && gasRecommendationFromAmount\n ? gasRecommendationFromAmount\n : undefined,\n options: {\n allowSwitchChain:\n subvariant === 'refuel' ? false : allowSwitchChain,\n bridges:\n allowBridges?.length || disabledBridges.length\n ? {\n allow: allowBridges,\n deny: disabledBridges.length\n ? disabledBridges\n : undefined,\n }\n : undefined,\n exchanges:\n allowExchanges?.length || disabledExchanges.length\n ? {\n allow: allowExchanges,\n deny: disabledExchanges.length\n ? disabledExchanges\n : undefined,\n }\n : undefined,\n order: routePriority,\n slippage: formattedSlippage,\n fee: calculatedFee || fee,\n },\n },\n { signal },\n );\n if (data.routes[0] && fromAddress) {\n // Update local tokens cache to keep priceUSD in sync\n const { fromToken, toToken } = data.routes[0];\n [fromToken, toToken].forEach((token) => {\n queryClient.setQueriesData(\n { queryKey: ['token-balances', fromAddress, token.chainId] },\n (data) => {\n if (data) {\n const clonedData = [...data];\n const index = clonedData.findIndex(\n (dataToken) => dataToken.address === token.address,\n );\n clonedData[index] = {\n ...clonedData[index],\n ...token,\n };\n return clonedData;\n }\n },\n );\n });\n }\n emitter.emit(WidgetEvent.AvailableRoutes, data.routes);\n return data;\n },\n enabled: isEnabled,\n staleTime: refetchTime,\n refetchInterval(query) {\n return Math.min(\n Math.abs(refetchTime - (Date.now() - query.state.dataUpdatedAt)),\n refetchTime,\n );\n },\n retry(failureCount, error: any) {\n if (failureCount >= 5) {\n return false;\n }\n if (error?.code === LiFiErrorCode.NotFound) {\n return false;\n }\n return true;\n },\n });\n\n const setReviewableRoute = (route: Route) => {\n const queryDataKey = queryKey.toSpliced(queryKey.length - 1, 1, route.id);\n queryClient.setQueryData(\n queryDataKey,\n { routes: [route] },\n { updatedAt: dataUpdatedAt },\n );\n setExecutableRoute(route);\n };\n\n return {\n routes: data?.routes,\n isLoading: isEnabled && isLoading,\n isFetching,\n isFetched,\n dataUpdatedAt,\n refetchTime,\n refetch,\n fromChain,\n toChain,\n queryKey,\n setReviewableRoute,\n };\n};\n","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getCircularProgressUtilityClass(slot) {\n return generateUtilityClass('MuiCircularProgress', slot);\n}\nconst circularProgressClasses = generateUtilityClasses('MuiCircularProgress', ['root', 'determinate', 'indeterminate', 'colorPrimary', 'colorSecondary', 'svg', 'circle', 'circleDeterminate', 'circleIndeterminate', 'circleDisableShrink']);\nexport default circularProgressClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\", \"color\", \"disableShrink\", \"size\", \"style\", \"thickness\", \"value\", \"variant\"];\nlet _ = t => t,\n _t,\n _t2,\n _t3,\n _t4;\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { keyframes, css } from '@mui/system';\nimport capitalize from '../utils/capitalize';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport { getCircularProgressUtilityClass } from './circularProgressClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst SIZE = 44;\nconst circularRotateKeyframe = keyframes(_t || (_t = _`\n 0% {\n transform: rotate(0deg);\n }\n\n 100% {\n transform: rotate(360deg);\n }\n`));\nconst circularDashKeyframe = keyframes(_t2 || (_t2 = _`\n 0% {\n stroke-dasharray: 1px, 200px;\n stroke-dashoffset: 0;\n }\n\n 50% {\n stroke-dasharray: 100px, 200px;\n stroke-dashoffset: -15px;\n }\n\n 100% {\n stroke-dasharray: 100px, 200px;\n stroke-dashoffset: -125px;\n }\n`));\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n variant,\n color,\n disableShrink\n } = ownerState;\n const slots = {\n root: ['root', variant, `color${capitalize(color)}`],\n svg: ['svg'],\n circle: ['circle', `circle${capitalize(variant)}`, disableShrink && 'circleDisableShrink']\n };\n return composeClasses(slots, getCircularProgressUtilityClass, classes);\n};\nconst CircularProgressRoot = styled('span', {\n name: 'MuiCircularProgress',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.variant], styles[`color${capitalize(ownerState.color)}`]];\n }\n})(({\n ownerState,\n theme\n}) => _extends({\n display: 'inline-block'\n}, ownerState.variant === 'determinate' && {\n transition: theme.transitions.create('transform')\n}, ownerState.color !== 'inherit' && {\n color: (theme.vars || theme).palette[ownerState.color].main\n}), ({\n ownerState\n}) => ownerState.variant === 'indeterminate' && css(_t3 || (_t3 = _`\n animation: ${0} 1.4s linear infinite;\n `), circularRotateKeyframe));\nconst CircularProgressSVG = styled('svg', {\n name: 'MuiCircularProgress',\n slot: 'Svg',\n overridesResolver: (props, styles) => styles.svg\n})({\n display: 'block' // Keeps the progress centered\n});\nconst CircularProgressCircle = styled('circle', {\n name: 'MuiCircularProgress',\n slot: 'Circle',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.circle, styles[`circle${capitalize(ownerState.variant)}`], ownerState.disableShrink && styles.circleDisableShrink];\n }\n})(({\n ownerState,\n theme\n}) => _extends({\n stroke: 'currentColor'\n}, ownerState.variant === 'determinate' && {\n transition: theme.transitions.create('stroke-dashoffset')\n}, ownerState.variant === 'indeterminate' && {\n // Some default value that looks fine waiting for the animation to kicks in.\n strokeDasharray: '80px, 200px',\n strokeDashoffset: 0 // Add the unit to fix a Edge 16 and below bug.\n}), ({\n ownerState\n}) => ownerState.variant === 'indeterminate' && !ownerState.disableShrink && css(_t4 || (_t4 = _`\n animation: ${0} 1.4s ease-in-out infinite;\n `), circularDashKeyframe));\n\n/**\n * ## ARIA\n *\n * If the progress bar is describing the loading progress of a particular region of a page,\n * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`\n * attribute to `true` on that region until it has finished loading.\n */\nconst CircularProgress = /*#__PURE__*/React.forwardRef(function CircularProgress(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCircularProgress'\n });\n const {\n className,\n color = 'primary',\n disableShrink = false,\n size = 40,\n style,\n thickness = 3.6,\n value = 0,\n variant = 'indeterminate'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n color,\n disableShrink,\n size,\n thickness,\n value,\n variant\n });\n const classes = useUtilityClasses(ownerState);\n const circleStyle = {};\n const rootStyle = {};\n const rootProps = {};\n if (variant === 'determinate') {\n const circumference = 2 * Math.PI * ((SIZE - thickness) / 2);\n circleStyle.strokeDasharray = circumference.toFixed(3);\n rootProps['aria-valuenow'] = Math.round(value);\n circleStyle.strokeDashoffset = `${((100 - value) / 100 * circumference).toFixed(3)}px`;\n rootStyle.transform = 'rotate(-90deg)';\n }\n return /*#__PURE__*/_jsx(CircularProgressRoot, _extends({\n className: clsx(classes.root, className),\n style: _extends({\n width: size,\n height: size\n }, rootStyle, style),\n ownerState: ownerState,\n ref: ref,\n role: \"progressbar\"\n }, rootProps, other, {\n children: /*#__PURE__*/_jsx(CircularProgressSVG, {\n className: classes.svg,\n ownerState: ownerState,\n viewBox: `${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`,\n children: /*#__PURE__*/_jsx(CircularProgressCircle, {\n className: classes.circle,\n style: circleStyle,\n ownerState: ownerState,\n cx: SIZE,\n cy: SIZE,\n r: (SIZE - thickness) / 2,\n fill: \"none\",\n strokeWidth: thickness\n })\n })\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? CircularProgress.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'primary'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * If `true`, the shrink animation is disabled.\n * This only works if variant is `indeterminate`.\n * @default false\n */\n disableShrink: chainPropTypes(PropTypes.bool, props => {\n if (props.disableShrink && props.variant && props.variant !== 'indeterminate') {\n return new Error('MUI: You have provided the `disableShrink` prop ' + 'with a variant other than `indeterminate`. This will have no effect.');\n }\n return null;\n }),\n /**\n * The size of the component.\n * If using a number, the pixel unit is assumed.\n * If using a string, you need to provide the CSS unit, for example '3rem'.\n * @default 40\n */\n size: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The thickness of the circle.\n * @default 3.6\n */\n thickness: PropTypes.number,\n /**\n * The value of the progress indicator for the determinate variant.\n * Value between 0 and 100.\n * @default 0\n */\n value: PropTypes.number,\n /**\n * The variant to use.\n * Use indeterminate when there is no progress value.\n * @default 'indeterminate'\n */\n variant: PropTypes.oneOf(['determinate', 'indeterminate'])\n} : void 0;\nexport default CircularProgress;","import generateUtilityClass from '@mui/utils/generateUtilityClass';\nimport generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nexport function getLoadingButtonUtilityClass(slot) {\n return generateUtilityClass('MuiLoadingButton', slot);\n}\nconst loadingButtonClasses = generateUtilityClasses('MuiLoadingButton', ['root', 'loading', 'loadingIndicator', 'loadingIndicatorCenter', 'loadingIndicatorStart', 'loadingIndicatorEnd', 'endIconLoadingEnd', 'startIconLoadingStart']);\nexport default loadingButtonClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"children\", \"disabled\", \"id\", \"loading\", \"loadingIndicator\", \"loadingPosition\", \"variant\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { chainPropTypes } from '@mui/utils';\nimport { capitalize, unstable_useId as useId } from '@mui/material/utils';\nimport { unstable_composeClasses as composeClasses } from '@mui/base';\nimport { styled } from '@mui/material/styles';\nimport { useDefaultProps } from '@mui/material/DefaultPropsProvider';\nimport Button from '@mui/material/Button';\nimport { ButtonGroupContext } from '@mui/material/ButtonGroup';\nimport CircularProgress from '@mui/material/CircularProgress';\nimport resolveProps from '@mui/utils/resolveProps';\nimport loadingButtonClasses, { getLoadingButtonUtilityClass } from './loadingButtonClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n loading,\n loadingPosition,\n classes\n } = ownerState;\n const slots = {\n root: ['root', loading && 'loading'],\n startIcon: [loading && `startIconLoading${capitalize(loadingPosition)}`],\n endIcon: [loading && `endIconLoading${capitalize(loadingPosition)}`],\n loadingIndicator: ['loadingIndicator', loading && `loadingIndicator${capitalize(loadingPosition)}`]\n };\n const composedClasses = composeClasses(slots, getLoadingButtonUtilityClass, classes);\n return _extends({}, classes, composedClasses);\n};\n\n// TODO use `import { rootShouldForwardProp } from '../styles/styled';` once move to core\nconst rootShouldForwardProp = prop => prop !== 'ownerState' && prop !== 'theme' && prop !== 'sx' && prop !== 'as' && prop !== 'classes';\nconst LoadingButtonRoot = styled(Button, {\n shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',\n name: 'MuiLoadingButton',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n return [styles.root, styles.startIconLoadingStart && {\n [`& .${loadingButtonClasses.startIconLoadingStart}`]: styles.startIconLoadingStart\n }, styles.endIconLoadingEnd && {\n [`& .${loadingButtonClasses.endIconLoadingEnd}`]: styles.endIconLoadingEnd\n }];\n }\n})(({\n ownerState,\n theme\n}) => _extends({\n [`& .${loadingButtonClasses.startIconLoadingStart}, & .${loadingButtonClasses.endIconLoadingEnd}`]: {\n transition: theme.transitions.create(['opacity'], {\n duration: theme.transitions.duration.short\n }),\n opacity: 0\n }\n}, ownerState.loadingPosition === 'center' && {\n transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color'], {\n duration: theme.transitions.duration.short\n }),\n [`&.${loadingButtonClasses.loading}`]: {\n color: 'transparent'\n }\n}, ownerState.loadingPosition === 'start' && ownerState.fullWidth && {\n [`& .${loadingButtonClasses.startIconLoadingStart}, & .${loadingButtonClasses.endIconLoadingEnd}`]: {\n transition: theme.transitions.create(['opacity'], {\n duration: theme.transitions.duration.short\n }),\n opacity: 0,\n marginRight: -8\n }\n}, ownerState.loadingPosition === 'end' && ownerState.fullWidth && {\n [`& .${loadingButtonClasses.startIconLoadingStart}, & .${loadingButtonClasses.endIconLoadingEnd}`]: {\n transition: theme.transitions.create(['opacity'], {\n duration: theme.transitions.duration.short\n }),\n opacity: 0,\n marginLeft: -8\n }\n}));\nconst LoadingButtonLoadingIndicator = styled('span', {\n name: 'MuiLoadingButton',\n slot: 'LoadingIndicator',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.loadingIndicator, styles[`loadingIndicator${capitalize(ownerState.loadingPosition)}`]];\n }\n})(({\n theme,\n ownerState\n}) => _extends({\n position: 'absolute',\n visibility: 'visible',\n display: 'flex'\n}, ownerState.loadingPosition === 'start' && (ownerState.variant === 'outlined' || ownerState.variant === 'contained') && {\n left: ownerState.size === 'small' ? 10 : 14\n}, ownerState.loadingPosition === 'start' && ownerState.variant === 'text' && {\n left: 6\n}, ownerState.loadingPosition === 'center' && {\n left: '50%',\n transform: 'translate(-50%)',\n color: (theme.vars || theme).palette.action.disabled\n}, ownerState.loadingPosition === 'end' && (ownerState.variant === 'outlined' || ownerState.variant === 'contained') && {\n right: ownerState.size === 'small' ? 10 : 14\n}, ownerState.loadingPosition === 'end' && ownerState.variant === 'text' && {\n right: 6\n}, ownerState.loadingPosition === 'start' && ownerState.fullWidth && {\n position: 'relative',\n left: -10\n}, ownerState.loadingPosition === 'end' && ownerState.fullWidth && {\n position: 'relative',\n right: -10\n}));\nconst LoadingButton = /*#__PURE__*/React.forwardRef(function LoadingButton(inProps, ref) {\n const contextProps = React.useContext(ButtonGroupContext);\n const resolvedProps = resolveProps(contextProps, inProps);\n const props = useDefaultProps({\n props: resolvedProps,\n name: 'MuiLoadingButton'\n });\n const {\n children,\n disabled = false,\n id: idProp,\n loading = false,\n loadingIndicator: loadingIndicatorProp,\n loadingPosition = 'center',\n variant = 'text'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const id = useId(idProp);\n const loadingIndicator = loadingIndicatorProp != null ? loadingIndicatorProp : /*#__PURE__*/_jsx(CircularProgress, {\n \"aria-labelledby\": id,\n color: \"inherit\",\n size: 16\n });\n const ownerState = _extends({}, props, {\n disabled,\n loading,\n loadingIndicator,\n loadingPosition,\n variant\n });\n const classes = useUtilityClasses(ownerState);\n const loadingButtonLoadingIndicator = loading ? /*#__PURE__*/_jsx(LoadingButtonLoadingIndicator, {\n className: classes.loadingIndicator,\n ownerState: ownerState,\n children: loadingIndicator\n }) : null;\n return /*#__PURE__*/_jsxs(LoadingButtonRoot, _extends({\n disabled: disabled || loading,\n id: id,\n ref: ref\n }, other, {\n variant: variant,\n classes: classes,\n ownerState: ownerState,\n children: [ownerState.loadingPosition === 'end' ? children : loadingButtonLoadingIndicator, ownerState.loadingPosition === 'end' ? loadingButtonLoadingIndicator : children]\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? LoadingButton.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * @ignore\n */\n id: PropTypes.string,\n /**\n * If `true`, the loading indicator is shown and the button becomes disabled.\n * @default false\n */\n loading: PropTypes.bool,\n /**\n * Element placed before the children if the button is in loading state.\n * The node should contain an element with `role=\"progressbar\"` with an accessible name.\n * By default we render a `CircularProgress` that is labelled by the button itself.\n * @default \n */\n loadingIndicator: PropTypes.node,\n /**\n * The loading indicator can be positioned on the start, end, or the center of the button.\n * @default 'center'\n */\n loadingPosition: chainPropTypes(PropTypes.oneOf(['start', 'end', 'center']), props => {\n if (props.loadingPosition === 'start' && !props.startIcon) {\n return new Error(`MUI: The loadingPosition=\"start\" should be used in combination with startIcon.`);\n }\n if (props.loadingPosition === 'end' && !props.endIcon) {\n return new Error(`MUI: The loadingPosition=\"end\" should be used in combination with endIcon.`);\n }\n return null;\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The variant to use.\n * @default 'text'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['contained', 'outlined', 'text']), PropTypes.string])\n} : void 0;\nexport default LoadingButton;","import { LoadingButton, loadingButtonClasses } from '@mui/lab';\nimport { styled } from '@mui/material';\nimport { getContrastAlphaColor } from '../utils/colors.js';\n\nexport const ButtonTertiary = styled(LoadingButton)(({ theme }) => ({\n color: theme.palette.text.primary,\n height: 40,\n fontSize: 14,\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n '&:hover, &:active': {\n backgroundColor: getContrastAlphaColor(theme, 0.08),\n },\n [`&.${loadingButtonClasses.loading}:disabled`]: {\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n },\n [`.${loadingButtonClasses.loadingIndicator}`]: {\n color: theme.palette.text.primary,\n },\n}));\n","import type { IconButtonProps } from '@mui/material';\nimport { Box, CircularProgress, IconButton, Tooltip } from '@mui/material';\nimport { useEffect, useState } from 'react';\nimport { Trans } from 'react-i18next';\n\nconst getProgressValue = (updatedAt: number, timeToUpdate: number) =>\n updatedAt\n ? Math.min(100, ((Date.now() - updatedAt) / timeToUpdate) * 100)\n : 0;\n\nconst getSecondsToUpdate = (updatedAt: number, timeToUpdate: number) =>\n Math.max(Math.round((timeToUpdate - (Date.now() - updatedAt)) / 1000), 0);\n\nexport const ProgressToNextUpdate: React.FC<\n {\n updatedAt: number;\n timeToUpdate: number;\n isLoading?: boolean;\n } & IconButtonProps\n> = ({ updatedAt, timeToUpdate, isLoading, onClick, ...other }) => {\n const [value, setValue] = useState(() =>\n getProgressValue(updatedAt, timeToUpdate),\n );\n\n useEffect(() => {\n setValue(getProgressValue(updatedAt, timeToUpdate));\n const id = setInterval(() => {\n const time = getProgressValue(updatedAt, timeToUpdate);\n setValue(time);\n if (time >= 100) {\n clearInterval(id);\n }\n }, 1000);\n return () => clearInterval(id);\n }, [timeToUpdate, updatedAt]);\n\n useEffect(() => {\n if (isLoading) {\n setValue(0);\n }\n }, [isLoading]);\n\n return (\n \n ]}\n />\n }\n >\n \n ({\n position: 'absolute',\n color:\n theme.palette.mode === 'light'\n ? theme.palette.grey[300]\n : theme.palette.grey[800],\n })}\n />\n ({\n opacity: value === 100 && !isLoading ? 0.5 : 1,\n color:\n theme.palette.mode === 'light'\n ? theme.palette.primary.main\n : theme.palette.primary.light,\n })}\n />\n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z\"\n}), 'ExpandLess');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z\"\n}), 'ExpandMore');","import type { IconButtonProps, LinkProps } from '@mui/material';\nimport { IconButton as MuiIconButton, styled } from '@mui/material';\nimport { getContrastAlphaColor } from '../../utils/colors.js';\n\nexport const CardIconButton = styled(MuiIconButton)<\n IconButtonProps & Pick\n>(({ theme }) => {\n return {\n padding: theme.spacing(0.5),\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n '&:hover': {\n backgroundColor: getContrastAlphaColor(theme, 0.08),\n },\n fontSize: '1rem',\n };\n});\n","import { Box, Typography, getContrastRatio, styled } from '@mui/material';\nimport { blend } from '../../utils/colors.js';\n\nexport const CardLabel = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'type',\n})<{ type?: 'active' }>(({ theme, type }) => {\n const backgroundColor =\n type === 'active'\n ? theme.palette.mode === 'light'\n ? theme.palette.secondary.main\n : blend(\n theme.palette.background.paper,\n theme.palette.secondary.main,\n 0.8,\n )\n : theme.palette.mode === 'light'\n ? blend(\n theme.palette.background.paper,\n theme.palette.common.black,\n 0.12,\n )\n : blend(\n theme.palette.background.paper,\n theme.palette.common.white,\n 0.16,\n );\n return {\n backgroundColor,\n borderRadius: theme.shape.borderRadius,\n color:\n getContrastRatio(theme.palette.common.white, backgroundColor) >= 3\n ? theme.palette.common.white\n : theme.palette.common.black,\n padding: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: 24,\n minWidth: 24,\n userSelect: 'none',\n fontSize: '1rem',\n marginRight: theme.spacing(1),\n };\n});\n\nexport const CardLabelTypography = styled(Typography, {\n shouldForwardProp: (prop) => prop !== 'type',\n})<{ type?: 'icon' }>(({ theme, type }) => ({\n padding:\n type === 'icon'\n ? theme.spacing(0.75, 0, 0.75, 0.75)\n : theme.spacing(0.75, 1.5),\n fontSize: 12,\n lineHeight: 1,\n fontWeight: '600',\n}));\n","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getStepperUtilityClass(slot) {\n return generateUtilityClass('MuiStepper', slot);\n}\nconst stepperClasses = generateUtilityClasses('MuiStepper', ['root', 'horizontal', 'vertical', 'nonLinear', 'alternativeLabel']);\nexport default stepperClasses;","import * as React from 'react';\n/**\n * Provides information about the current step in Stepper.\n */\nconst StepperContext = /*#__PURE__*/React.createContext({});\nif (process.env.NODE_ENV !== 'production') {\n StepperContext.displayName = 'StepperContext';\n}\n\n/**\n * Returns the current StepperContext or an empty object if no StepperContext\n * has been defined in the component tree.\n */\nexport function useStepperContext() {\n return React.useContext(StepperContext);\n}\nexport default StepperContext;","import * as React from 'react';\n/**\n * Provides information about the current step in Stepper.\n */\nconst StepContext = /*#__PURE__*/React.createContext({});\nif (process.env.NODE_ENV !== 'production') {\n StepContext.displayName = 'StepContext';\n}\n\n/**\n * Returns the current StepContext or an empty object if no StepContext\n * has been defined in the component tree.\n */\nexport function useStepContext() {\n return React.useContext(StepContext);\n}\nexport default StepContext;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getStepConnectorUtilityClass(slot) {\n return generateUtilityClass('MuiStepConnector', slot);\n}\nconst stepConnectorClasses = generateUtilityClasses('MuiStepConnector', ['root', 'horizontal', 'vertical', 'alternativeLabel', 'active', 'completed', 'disabled', 'line', 'lineHorizontal', 'lineVertical']);\nexport default stepConnectorClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport capitalize from '../utils/capitalize';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport StepperContext from '../Stepper/StepperContext';\nimport StepContext from '../Step/StepContext';\nimport { getStepConnectorUtilityClass } from './stepConnectorClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n orientation,\n alternativeLabel,\n active,\n completed,\n disabled\n } = ownerState;\n const slots = {\n root: ['root', orientation, alternativeLabel && 'alternativeLabel', active && 'active', completed && 'completed', disabled && 'disabled'],\n line: ['line', `line${capitalize(orientation)}`]\n };\n return composeClasses(slots, getStepConnectorUtilityClass, classes);\n};\nconst StepConnectorRoot = styled('div', {\n name: 'MuiStepConnector',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.orientation], ownerState.alternativeLabel && styles.alternativeLabel, ownerState.completed && styles.completed];\n }\n})(({\n ownerState\n}) => _extends({\n flex: '1 1 auto'\n}, ownerState.orientation === 'vertical' && {\n marginLeft: 12 // half icon\n}, ownerState.alternativeLabel && {\n position: 'absolute',\n top: 8 + 4,\n left: 'calc(-50% + 20px)',\n right: 'calc(50% + 20px)'\n}));\nconst StepConnectorLine = styled('span', {\n name: 'MuiStepConnector',\n slot: 'Line',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.line, styles[`line${capitalize(ownerState.orientation)}`]];\n }\n})(({\n ownerState,\n theme\n}) => {\n const borderColor = theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[600];\n return _extends({\n display: 'block',\n borderColor: theme.vars ? theme.vars.palette.StepConnector.border : borderColor\n }, ownerState.orientation === 'horizontal' && {\n borderTopStyle: 'solid',\n borderTopWidth: 1\n }, ownerState.orientation === 'vertical' && {\n borderLeftStyle: 'solid',\n borderLeftWidth: 1,\n minHeight: 24\n });\n});\nconst StepConnector = /*#__PURE__*/React.forwardRef(function StepConnector(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiStepConnector'\n });\n const {\n className\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const {\n alternativeLabel,\n orientation = 'horizontal'\n } = React.useContext(StepperContext);\n const {\n active,\n disabled,\n completed\n } = React.useContext(StepContext);\n const ownerState = _extends({}, props, {\n alternativeLabel,\n orientation,\n active,\n completed,\n disabled\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(StepConnectorRoot, _extends({\n className: clsx(classes.root, className),\n ref: ref,\n ownerState: ownerState\n }, other, {\n children: /*#__PURE__*/_jsx(StepConnectorLine, {\n className: classes.line,\n ownerState: ownerState\n })\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? StepConnector.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default StepConnector;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"activeStep\", \"alternativeLabel\", \"children\", \"className\", \"component\", \"connector\", \"nonLinear\", \"orientation\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport integerPropType from '@mui/utils/integerPropType';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport { getStepperUtilityClass } from './stepperClasses';\nimport StepConnector from '../StepConnector';\nimport StepperContext from './StepperContext';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n orientation,\n nonLinear,\n alternativeLabel,\n classes\n } = ownerState;\n const slots = {\n root: ['root', orientation, nonLinear && 'nonLinear', alternativeLabel && 'alternativeLabel']\n };\n return composeClasses(slots, getStepperUtilityClass, classes);\n};\nconst StepperRoot = styled('div', {\n name: 'MuiStepper',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.orientation], ownerState.alternativeLabel && styles.alternativeLabel, ownerState.nonLinear && styles.nonLinear];\n }\n})(({\n ownerState\n}) => _extends({\n display: 'flex'\n}, ownerState.orientation === 'horizontal' && {\n flexDirection: 'row',\n alignItems: 'center'\n}, ownerState.orientation === 'vertical' && {\n flexDirection: 'column'\n}, ownerState.alternativeLabel && {\n alignItems: 'flex-start'\n}));\nconst defaultConnector = /*#__PURE__*/_jsx(StepConnector, {});\nconst Stepper = /*#__PURE__*/React.forwardRef(function Stepper(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiStepper'\n });\n const {\n activeStep = 0,\n alternativeLabel = false,\n children,\n className,\n component = 'div',\n connector = defaultConnector,\n nonLinear = false,\n orientation = 'horizontal'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n nonLinear,\n alternativeLabel,\n orientation,\n component\n });\n const classes = useUtilityClasses(ownerState);\n const childrenArray = React.Children.toArray(children).filter(Boolean);\n const steps = childrenArray.map((step, index) => {\n return /*#__PURE__*/React.cloneElement(step, _extends({\n index,\n last: index + 1 === childrenArray.length\n }, step.props));\n });\n const contextValue = React.useMemo(() => ({\n activeStep,\n alternativeLabel,\n connector,\n nonLinear,\n orientation\n }), [activeStep, alternativeLabel, connector, nonLinear, orientation]);\n return /*#__PURE__*/_jsx(StepperContext.Provider, {\n value: contextValue,\n children: /*#__PURE__*/_jsx(StepperRoot, _extends({\n as: component,\n ownerState: ownerState,\n className: clsx(classes.root, className),\n ref: ref\n }, other, {\n children: steps\n }))\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Stepper.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Set the active step (zero based index).\n * Set to -1 to disable all the steps.\n * @default 0\n */\n activeStep: integerPropType,\n /**\n * If set to 'true' and orientation is horizontal,\n * then the step label will be positioned under the icon.\n * @default false\n */\n alternativeLabel: PropTypes.bool,\n /**\n * Two or more `` components.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * An element to be placed between each step.\n * @default \n */\n connector: PropTypes.element,\n /**\n * If set the `Stepper` will not assist in controlling steps for linear flow.\n * @default false\n */\n nonLinear: PropTypes.bool,\n /**\n * The component orientation (layout flow direction).\n * @default 'horizontal'\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default Stepper;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getStepUtilityClass(slot) {\n return generateUtilityClass('MuiStep', slot);\n}\nconst stepClasses = generateUtilityClasses('MuiStep', ['root', 'horizontal', 'vertical', 'alternativeLabel', 'completed']);\nexport default stepClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"active\", \"children\", \"className\", \"component\", \"completed\", \"disabled\", \"expanded\", \"index\", \"last\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport integerPropType from '@mui/utils/integerPropType';\nimport composeClasses from '@mui/utils/composeClasses';\nimport StepperContext from '../Stepper/StepperContext';\nimport StepContext from './StepContext';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport { getStepUtilityClass } from './stepClasses';\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n orientation,\n alternativeLabel,\n completed\n } = ownerState;\n const slots = {\n root: ['root', orientation, alternativeLabel && 'alternativeLabel', completed && 'completed']\n };\n return composeClasses(slots, getStepUtilityClass, classes);\n};\nconst StepRoot = styled('div', {\n name: 'MuiStep',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.orientation], ownerState.alternativeLabel && styles.alternativeLabel, ownerState.completed && styles.completed];\n }\n})(({\n ownerState\n}) => _extends({}, ownerState.orientation === 'horizontal' && {\n paddingLeft: 8,\n paddingRight: 8\n}, ownerState.alternativeLabel && {\n flex: 1,\n position: 'relative'\n}));\nconst Step = /*#__PURE__*/React.forwardRef(function Step(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiStep'\n });\n const {\n active: activeProp,\n children,\n className,\n component = 'div',\n completed: completedProp,\n disabled: disabledProp,\n expanded = false,\n index,\n last\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const {\n activeStep,\n connector,\n alternativeLabel,\n orientation,\n nonLinear\n } = React.useContext(StepperContext);\n let [active = false, completed = false, disabled = false] = [activeProp, completedProp, disabledProp];\n if (activeStep === index) {\n active = activeProp !== undefined ? activeProp : true;\n } else if (!nonLinear && activeStep > index) {\n completed = completedProp !== undefined ? completedProp : true;\n } else if (!nonLinear && activeStep < index) {\n disabled = disabledProp !== undefined ? disabledProp : true;\n }\n const contextValue = React.useMemo(() => ({\n index,\n last,\n expanded,\n icon: index + 1,\n active,\n completed,\n disabled\n }), [index, last, expanded, active, completed, disabled]);\n const ownerState = _extends({}, props, {\n active,\n orientation,\n alternativeLabel,\n completed,\n disabled,\n expanded,\n component\n });\n const classes = useUtilityClasses(ownerState);\n const newChildren = /*#__PURE__*/_jsxs(StepRoot, _extends({\n as: component,\n className: clsx(classes.root, className),\n ref: ref,\n ownerState: ownerState\n }, other, {\n children: [connector && alternativeLabel && index !== 0 ? connector : null, children]\n }));\n return /*#__PURE__*/_jsx(StepContext.Provider, {\n value: contextValue,\n children: connector && !alternativeLabel && index !== 0 ? /*#__PURE__*/_jsxs(React.Fragment, {\n children: [connector, newChildren]\n }) : newChildren\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Step.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Sets the step as active. Is passed to child components.\n */\n active: PropTypes.bool,\n /**\n * Should be `Step` sub-components such as `StepLabel`, `StepContent`.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * Mark the step as completed. Is passed to child components.\n */\n completed: PropTypes.bool,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, the step is disabled, will also disable the button if\n * `StepButton` is a child of `Step`. Is passed to child components.\n */\n disabled: PropTypes.bool,\n /**\n * Expand the step.\n * @default false\n */\n expanded: PropTypes.bool,\n /**\n * The position of the step.\n * The prop defaults to the value inherited from the parent Stepper component.\n */\n index: integerPropType,\n /**\n * If `true`, the Step is displayed as rendered last.\n * The prop defaults to the value inherited from the parent Stepper component.\n */\n last: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default Step;","export const LiFiToolLogo =\n \"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none'%3e %3ccircle cx='16' cy='16' r='16' fill='%23F5B5FF'/%3e %3cpath fill='black' d='m15.503 19.203-5.334 1.235a.468.468 0 0 0-.34.439v3.672c0 .308.243.503.55.438l7.443-1.722c.308-.065.437-.357.308-.634l-1.346-2.778c-.21-.439 0-.894.47-.991l4.864-1.17c.34-.081.632-.439.632-.796V13.5c0-.309-.243-.52-.551-.439l-7.02 1.674c-.438.097-.633.52-.438.926l1.232 2.551c.211.439 0 .877-.47.991'/%3e %3cpath fill='black' d='m11.985 10.023 1.394 2.86c.179.374 0 .764-.405.845l-2.578.601c-.324.081-.584.406-.584.731v3.07c0 .52.422.846.925.732l2.4-.552c.323-.065.583-.406.583-.732l.016-3.151c0-.44.357-.878.778-.975l7.863-1.885a.468.468 0 0 0 .34-.439V7.456c0-.309-.242-.52-.55-.439L12.293 9.39c-.308.065-.438.357-.308.633'/%3e %3c/svg%3e\";\n","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M12 0a12 12 0 1 0 0 24 12 12 0 0 0 0-24zm-2 17l-5-5 1.4-1.4 3.6 3.6 7.6-7.6L19 8l-9 9z\"\n}), 'CheckCircle');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z\"\n}), 'Warning');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getStepIconUtilityClass(slot) {\n return generateUtilityClass('MuiStepIcon', slot);\n}\nconst stepIconClasses = generateUtilityClasses('MuiStepIcon', ['root', 'active', 'completed', 'error', 'text']);\nexport default stepIconClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nvar _circle;\nconst _excluded = [\"active\", \"className\", \"completed\", \"error\", \"icon\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport CheckCircle from '../internal/svg-icons/CheckCircle';\nimport Warning from '../internal/svg-icons/Warning';\nimport SvgIcon from '../SvgIcon';\nimport stepIconClasses, { getStepIconUtilityClass } from './stepIconClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n active,\n completed,\n error\n } = ownerState;\n const slots = {\n root: ['root', active && 'active', completed && 'completed', error && 'error'],\n text: ['text']\n };\n return composeClasses(slots, getStepIconUtilityClass, classes);\n};\nconst StepIconRoot = styled(SvgIcon, {\n name: 'MuiStepIcon',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})(({\n theme\n}) => ({\n display: 'block',\n transition: theme.transitions.create('color', {\n duration: theme.transitions.duration.shortest\n }),\n color: (theme.vars || theme).palette.text.disabled,\n [`&.${stepIconClasses.completed}`]: {\n color: (theme.vars || theme).palette.primary.main\n },\n [`&.${stepIconClasses.active}`]: {\n color: (theme.vars || theme).palette.primary.main\n },\n [`&.${stepIconClasses.error}`]: {\n color: (theme.vars || theme).palette.error.main\n }\n}));\nconst StepIconText = styled('text', {\n name: 'MuiStepIcon',\n slot: 'Text',\n overridesResolver: (props, styles) => styles.text\n})(({\n theme\n}) => ({\n fill: (theme.vars || theme).palette.primary.contrastText,\n fontSize: theme.typography.caption.fontSize,\n fontFamily: theme.typography.fontFamily\n}));\nconst StepIcon = /*#__PURE__*/React.forwardRef(function StepIcon(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiStepIcon'\n });\n const {\n active = false,\n className: classNameProp,\n completed = false,\n error = false,\n icon\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n active,\n completed,\n error\n });\n const classes = useUtilityClasses(ownerState);\n if (typeof icon === 'number' || typeof icon === 'string') {\n const className = clsx(classNameProp, classes.root);\n if (error) {\n return /*#__PURE__*/_jsx(StepIconRoot, _extends({\n as: Warning,\n className: className,\n ref: ref,\n ownerState: ownerState\n }, other));\n }\n if (completed) {\n return /*#__PURE__*/_jsx(StepIconRoot, _extends({\n as: CheckCircle,\n className: className,\n ref: ref,\n ownerState: ownerState\n }, other));\n }\n return /*#__PURE__*/_jsxs(StepIconRoot, _extends({\n className: className,\n ref: ref,\n ownerState: ownerState\n }, other, {\n children: [_circle || (_circle = /*#__PURE__*/_jsx(\"circle\", {\n cx: \"12\",\n cy: \"12\",\n r: \"12\"\n })), /*#__PURE__*/_jsx(StepIconText, {\n className: classes.text,\n x: \"12\",\n y: \"12\",\n textAnchor: \"middle\",\n dominantBaseline: \"central\",\n ownerState: ownerState,\n children: icon\n })]\n }));\n }\n return icon;\n});\nprocess.env.NODE_ENV !== \"production\" ? StepIcon.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Whether this step is active.\n * @default false\n */\n active: PropTypes.bool,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * Mark the step as completed. Is passed to child components.\n * @default false\n */\n completed: PropTypes.bool,\n /**\n * If `true`, the step is marked as failed.\n * @default false\n */\n error: PropTypes.bool,\n /**\n * The label displayed in the step icon.\n */\n icon: PropTypes.node,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default StepIcon;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getStepLabelUtilityClass(slot) {\n return generateUtilityClass('MuiStepLabel', slot);\n}\nconst stepLabelClasses = generateUtilityClasses('MuiStepLabel', ['root', 'horizontal', 'vertical', 'label', 'active', 'completed', 'error', 'disabled', 'iconContainer', 'alternativeLabel', 'labelContainer']);\nexport default stepLabelClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"children\", \"className\", \"componentsProps\", \"error\", \"icon\", \"optional\", \"slotProps\", \"StepIconComponent\", \"StepIconProps\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport StepIcon from '../StepIcon';\nimport StepperContext from '../Stepper/StepperContext';\nimport StepContext from '../Step/StepContext';\nimport stepLabelClasses, { getStepLabelUtilityClass } from './stepLabelClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n orientation,\n active,\n completed,\n error,\n disabled,\n alternativeLabel\n } = ownerState;\n const slots = {\n root: ['root', orientation, error && 'error', disabled && 'disabled', alternativeLabel && 'alternativeLabel'],\n label: ['label', active && 'active', completed && 'completed', error && 'error', disabled && 'disabled', alternativeLabel && 'alternativeLabel'],\n iconContainer: ['iconContainer', active && 'active', completed && 'completed', error && 'error', disabled && 'disabled', alternativeLabel && 'alternativeLabel'],\n labelContainer: ['labelContainer', alternativeLabel && 'alternativeLabel']\n };\n return composeClasses(slots, getStepLabelUtilityClass, classes);\n};\nconst StepLabelRoot = styled('span', {\n name: 'MuiStepLabel',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.orientation]];\n }\n})(({\n ownerState\n}) => _extends({\n display: 'flex',\n alignItems: 'center',\n [`&.${stepLabelClasses.alternativeLabel}`]: {\n flexDirection: 'column'\n },\n [`&.${stepLabelClasses.disabled}`]: {\n cursor: 'default'\n }\n}, ownerState.orientation === 'vertical' && {\n textAlign: 'left',\n padding: '8px 0'\n}));\nconst StepLabelLabel = styled('span', {\n name: 'MuiStepLabel',\n slot: 'Label',\n overridesResolver: (props, styles) => styles.label\n})(({\n theme\n}) => _extends({}, theme.typography.body2, {\n display: 'block',\n transition: theme.transitions.create('color', {\n duration: theme.transitions.duration.shortest\n }),\n [`&.${stepLabelClasses.active}`]: {\n color: (theme.vars || theme).palette.text.primary,\n fontWeight: 500\n },\n [`&.${stepLabelClasses.completed}`]: {\n color: (theme.vars || theme).palette.text.primary,\n fontWeight: 500\n },\n [`&.${stepLabelClasses.alternativeLabel}`]: {\n marginTop: 16\n },\n [`&.${stepLabelClasses.error}`]: {\n color: (theme.vars || theme).palette.error.main\n }\n}));\nconst StepLabelIconContainer = styled('span', {\n name: 'MuiStepLabel',\n slot: 'IconContainer',\n overridesResolver: (props, styles) => styles.iconContainer\n})(() => ({\n flexShrink: 0,\n // Fix IE11 issue\n display: 'flex',\n paddingRight: 8,\n [`&.${stepLabelClasses.alternativeLabel}`]: {\n paddingRight: 0\n }\n}));\nconst StepLabelLabelContainer = styled('span', {\n name: 'MuiStepLabel',\n slot: 'LabelContainer',\n overridesResolver: (props, styles) => styles.labelContainer\n})(({\n theme\n}) => ({\n width: '100%',\n color: (theme.vars || theme).palette.text.secondary,\n [`&.${stepLabelClasses.alternativeLabel}`]: {\n textAlign: 'center'\n }\n}));\nconst StepLabel = /*#__PURE__*/React.forwardRef(function StepLabel(inProps, ref) {\n var _slotProps$label;\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiStepLabel'\n });\n const {\n children,\n className,\n componentsProps = {},\n error = false,\n icon: iconProp,\n optional,\n slotProps = {},\n StepIconComponent: StepIconComponentProp,\n StepIconProps\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const {\n alternativeLabel,\n orientation\n } = React.useContext(StepperContext);\n const {\n active,\n disabled,\n completed,\n icon: iconContext\n } = React.useContext(StepContext);\n const icon = iconProp || iconContext;\n let StepIconComponent = StepIconComponentProp;\n if (icon && !StepIconComponent) {\n StepIconComponent = StepIcon;\n }\n const ownerState = _extends({}, props, {\n active,\n alternativeLabel,\n completed,\n disabled,\n error,\n orientation\n });\n const classes = useUtilityClasses(ownerState);\n const labelSlotProps = (_slotProps$label = slotProps.label) != null ? _slotProps$label : componentsProps.label;\n return /*#__PURE__*/_jsxs(StepLabelRoot, _extends({\n className: clsx(classes.root, className),\n ref: ref,\n ownerState: ownerState\n }, other, {\n children: [icon || StepIconComponent ? /*#__PURE__*/_jsx(StepLabelIconContainer, {\n className: classes.iconContainer,\n ownerState: ownerState,\n children: /*#__PURE__*/_jsx(StepIconComponent, _extends({\n completed: completed,\n active: active,\n error: error,\n icon: icon\n }, StepIconProps))\n }) : null, /*#__PURE__*/_jsxs(StepLabelLabelContainer, {\n className: classes.labelContainer,\n ownerState: ownerState,\n children: [children ? /*#__PURE__*/_jsx(StepLabelLabel, _extends({\n ownerState: ownerState\n }, labelSlotProps, {\n className: clsx(classes.label, labelSlotProps == null ? void 0 : labelSlotProps.className),\n children: children\n })) : null, optional]\n })]\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? StepLabel.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * In most cases will simply be a string containing a title for the label.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The props used for each slot inside.\n * @default {}\n */\n componentsProps: PropTypes.shape({\n label: PropTypes.object\n }),\n /**\n * If `true`, the step is marked as failed.\n * @default false\n */\n error: PropTypes.bool,\n /**\n * Override the default label of the step icon.\n */\n icon: PropTypes.node,\n /**\n * The optional node to display.\n */\n optional: PropTypes.node,\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes.shape({\n label: PropTypes.object\n }),\n /**\n * The component to render in place of the [`StepIcon`](/material-ui/api/step-icon/).\n */\n StepIconComponent: PropTypes.elementType,\n /**\n * Props applied to the [`StepIcon`](/material-ui/api/step-icon/) element.\n */\n StepIconProps: PropTypes.object,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nStepLabel.muiName = 'StepLabel';\nexport default StepLabel;","import {\n Box,\n StepConnector as MuiStepConnector,\n StepLabel as MuiStepLabel,\n Typography,\n alpha,\n stepConnectorClasses,\n stepLabelClasses,\n styled,\n} from '@mui/material';\nimport { AvatarMasked } from '../Avatar/Avatar.style.js';\n\nexport const StepConnector = styled(MuiStepConnector, {\n shouldForwardProp: (prop) =>\n !['active', 'completed', 'error'].includes(prop as string),\n})(({ theme }) => ({\n marginLeft: theme.spacing(2.375),\n [`.${stepConnectorClasses.line}`]: {\n minHeight: 8,\n borderLeftWidth: 2,\n borderColor:\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, 0.12)\n : alpha(theme.palette.common.white, 0.16),\n },\n}));\n\nexport const StepLabel = styled(MuiStepLabel, {\n shouldForwardProp: (prop) =>\n !['active', 'completed', 'error', 'disabled'].includes(prop as string),\n})(({ theme }) => ({\n padding: 0,\n alignItems: 'center',\n [`.${stepLabelClasses.iconContainer}`]: {\n paddingLeft: theme.spacing(1.25),\n paddingRight: theme.spacing(3.25),\n },\n [`.${stepLabelClasses.labelContainer}`]: {\n minHeight: 24,\n display: 'flex',\n alignItems: 'center',\n },\n [`&.${stepLabelClasses.disabled}`]: {\n cursor: 'inherit',\n },\n}));\n\nexport const StepLabelTypography = styled(Typography)(({ theme }) => ({\n fontSize: 12,\n fontWeight: 500,\n lineHeight: 1.325,\n color: theme.palette.text.secondary,\n padding: theme.spacing(0.5, 0),\n}));\n\nexport const StepContent = styled(Box, {\n shouldForwardProp: (prop) => !['last'].includes(prop as string),\n})<{ last: boolean }>(({ theme, last }) => ({\n borderLeft: last\n ? 'none'\n : `2px solid ${\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, 0.12)\n : alpha(theme.palette.common.white, 0.16)\n }`,\n margin: theme.spacing(0, 0, 0, 2.375),\n paddingLeft: last ? theme.spacing(4.625) : theme.spacing(4.375),\n}));\n\nexport const StepAvatar = styled(AvatarMasked)(({ theme }) => ({\n color: theme.palette.text.primary,\n backgroundColor: 'transparent',\n}));\n","import type { FeeCost, GasCost, RouteExtended, Token } from '@lifi/sdk';\nimport { formatUnits } from 'viem';\n\nexport interface FeesBreakdown {\n amount: bigint;\n amountUSD: number;\n token: Token;\n}\n\nexport const getAccumulatedFeeCostsBreakdown = (\n route: RouteExtended,\n included: boolean = false,\n) => {\n const gasCosts = getGasCostsBreakdown(route);\n const feeCosts = getFeeCostsBreakdown(route, included);\n const gasCostUSD = gasCosts.reduce(\n (sum, gasCost) => sum + gasCost.amountUSD,\n 0,\n );\n const feeCostUSD = feeCosts.reduce(\n (sum, feeCost) => sum + feeCost.amountUSD,\n 0,\n );\n const combinedFeesUSD = gasCostUSD + feeCostUSD;\n return {\n gasCosts,\n feeCosts,\n gasCostUSD,\n feeCostUSD,\n combinedFeesUSD,\n };\n};\n\nexport const getGasCostsBreakdown = (route: RouteExtended): FeesBreakdown[] => {\n return Array.from(\n route.steps\n .reduce((groupedGasCosts, step) => {\n const gasCosts = step.execution?.gasCosts ?? step.estimate.gasCosts;\n if (gasCosts?.length) {\n const {\n token,\n amount: gasCostAmount,\n amountUSD: gasCostAmountUSD,\n } = getStepFeeCostsBreakdown(gasCosts);\n const groupedGasCost = groupedGasCosts.get(token.chainId);\n const amount = groupedGasCost\n ? groupedGasCost.amount + gasCostAmount\n : gasCostAmount;\n const amountUSD = groupedGasCost\n ? groupedGasCost.amountUSD + gasCostAmountUSD\n : gasCostAmountUSD;\n groupedGasCosts.set(token.chainId, {\n amount,\n amountUSD,\n token,\n });\n return groupedGasCosts;\n }\n return groupedGasCosts;\n }, new Map())\n .values(),\n );\n};\n\nexport const getFeeCostsBreakdown = (\n route: RouteExtended,\n included?: boolean,\n): FeesBreakdown[] => {\n return Array.from(\n route.steps\n .reduce((groupedFeeCosts, step) => {\n let feeCosts = step.execution?.feeCosts ?? step.estimate.feeCosts;\n if (typeof included === 'boolean') {\n feeCosts = feeCosts?.filter(\n (feeCost) => feeCost.included === included,\n );\n }\n if (feeCosts?.length) {\n const {\n token,\n amount: feeCostAmount,\n amountUSD: feeCostAmountUSD,\n } = getStepFeeCostsBreakdown(feeCosts);\n const groupedFeeCost = groupedFeeCosts.get(token.chainId);\n const amount = groupedFeeCost\n ? groupedFeeCost.amount + feeCostAmount\n : feeCostAmount;\n const amountUSD = groupedFeeCost\n ? groupedFeeCost.amountUSD + feeCostAmountUSD\n : feeCostAmountUSD;\n groupedFeeCosts.set(token.chainId, {\n amount,\n amountUSD,\n token,\n });\n return groupedFeeCosts;\n }\n return groupedFeeCosts;\n }, new Map())\n .values(),\n );\n};\n\nexport const getStepFeeCostsBreakdown = (\n feeCosts: FeeCost[] | GasCost[],\n): FeesBreakdown => {\n const token = feeCosts[0].token;\n const amount = feeCosts.reduce(\n (amount, feeCost) => amount + BigInt(feeCost.amount || 0),\n 0n,\n );\n const amountUSD = feeCosts.reduce(\n (amount, feeCost) =>\n amount +\n parseFloat(feeCost.token.priceUSD || '0') *\n parseFloat(\n formatUnits(BigInt(feeCost.amount || 0), feeCost.token.decimals),\n ),\n 0,\n );\n return {\n amount,\n amountUSD,\n token,\n };\n};\n","import type { LiFiStepExtended } from '@lifi/sdk';\nimport type { TypographyProps } from '@mui/material';\nimport { Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { getStepFeeCostsBreakdown } from '../../utils/fees.js';\n\nexport const StepFees: React.FC<\n TypographyProps & {\n step: LiFiStepExtended;\n }\n> = ({ step, ...other }) => {\n const { t } = useTranslation();\n\n const isDone = step.execution?.status === 'DONE';\n const gasCosts = step.execution?.gasCosts ?? step.estimate.gasCosts;\n const feeCosts = step.execution?.feeCosts ?? step.estimate.feeCosts;\n let fees = 0;\n\n if (gasCosts) {\n const { amountUSD } = getStepFeeCostsBreakdown(gasCosts);\n fees += amountUSD;\n }\n\n if (feeCosts) {\n const filteredfeeCosts = feeCosts?.filter((fee) => !fee.included);\n if (filteredfeeCosts?.length) {\n const { amountUSD } = getStepFeeCostsBreakdown(filteredfeeCosts);\n fees += amountUSD;\n }\n }\n\n return (\n \n {t(`format.currency`, { value: fees })}{' '}\n {isDone ? t('main.fees.paid') : t('main.fees.estimated')}\n \n );\n};\n","import type { LiFiStep, StepExtended } from '@lifi/sdk';\nimport { ArrowForward, ExpandLess, ExpandMore } from '@mui/icons-material';\nimport type { StepIconProps } from '@mui/material';\nimport {\n Badge,\n Box,\n Collapse,\n Step as MuiStep,\n Stepper,\n Typography,\n} from '@mui/material';\nimport type { MouseEventHandler } from 'react';\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { formatUnits } from 'viem';\nimport { useAvailableChains } from '../../hooks/useAvailableChains.js';\nimport { LiFiToolLogo } from '../../icons/lifi.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport { formatTokenAmount } from '../../utils/format.js';\nimport { CardIconButton } from '../Card/CardIconButton.js';\nimport { SmallAvatar } from '../SmallAvatar.js';\nimport {\n StepAvatar,\n StepConnector,\n StepContent,\n StepLabel,\n StepLabelTypography,\n} from './StepActions.style.js';\nimport { StepFees } from './StepFees.js';\nimport type {\n IncludedStepsProps,\n StepActionsProps,\n StepDetailsLabelProps,\n} from './types.js';\n\nexport const StepActions: React.FC = ({\n step,\n dense,\n ...other\n}) => {\n const { t } = useTranslation();\n const { subvariant } = useWidgetConfig();\n const [cardExpanded, setCardExpanded] = useState(false);\n\n const handleExpand: MouseEventHandler = (e) => {\n e.stopPropagation();\n setCardExpanded((expanded) => !expanded);\n };\n\n // FIXME: step transaction request overrides step tool details, but not included step tool details\n const toolDetails =\n subvariant === 'custom'\n ? step.includedSteps.find(\n (step) => step.tool === 'custom' && step.toolDetails.key !== 'custom',\n )?.toolDetails || step.toolDetails\n : step.toolDetails;\n\n return (\n \n \n }\n >\n \n {toolDetails.name[0]}\n \n \n \n \n {toolDetails.name?.includes('LI.FI')\n ? toolDetails.name\n : t(`main.stepDetails`, {\n tool: toolDetails.name,\n })}\n \n \n \n {dense ? (\n \n {cardExpanded ? (\n \n ) : (\n \n )}\n \n ) : null}\n \n {dense ? (\n \n \n \n ) : (\n \n )}\n \n );\n};\n\nexport const IncludedSteps: React.FC = ({ step }) => {\n const { subvariant, subvariantOptions, feeConfig, hiddenUI } =\n useWidgetConfig();\n\n let includedSteps = step.includedSteps;\n if (hiddenUI?.includes(HiddenUI.IntegratorStepDetails)) {\n const feeCollectionStep = includedSteps.find(\n (step) => step.tool === 'feeCollection',\n );\n if (feeCollectionStep) {\n includedSteps = structuredClone(\n includedSteps.filter((step) => step.tool !== 'feeCollection'),\n );\n includedSteps[0].estimate.fromAmount =\n feeCollectionStep.estimate.fromAmount;\n }\n }\n\n // eslint-disable-next-line react/no-unstable-nested-components\n const StepIconComponent = ({ icon }: StepIconProps) => {\n const includedStep = includedSteps?.[Number(icon) - 1];\n const feeCollectionStep =\n includedStep?.type === 'protocol' &&\n includedStep?.tool === 'feeCollection';\n const toolName =\n feeCollectionStep && feeConfig?.name\n ? feeConfig?.name\n : includedStep?.toolDetails.name;\n const toolLogoURI =\n feeCollectionStep && feeConfig?.logoURI\n ? feeConfig?.logoURI\n : includedStep?.toolDetails.logoURI;\n return toolLogoURI ? (\n \n {toolName?.[0]}\n \n ) : null;\n };\n\n return (\n \n }\n activeStep={-1}\n >\n {includedSteps.map((step, i, includedSteps) => (\n \n \n {step.type === 'custom' && subvariant === 'custom' ? (\n \n ) : step.type === 'cross' ? (\n \n ) : step.type === 'protocol' ? (\n \n ) : (\n \n )}\n \n \n \n \n \n ))}\n \n \n );\n};\n\nexport const StepDetailsContent: React.FC<{\n step: StepExtended;\n}> = ({ step }) => {\n const { t } = useTranslation();\n\n const sameTokenProtocolStep =\n step.action.fromToken.chainId === step.action.toToken.chainId &&\n step.action.fromToken.address === step.action.toToken.address;\n\n let fromAmount: string | undefined;\n if (sameTokenProtocolStep) {\n const estimatedFromAmount =\n BigInt(step.estimate.fromAmount) - BigInt(step.estimate.toAmount);\n\n fromAmount =\n estimatedFromAmount > 0n\n ? formatUnits(estimatedFromAmount, step.action.fromToken.decimals)\n : formatUnits(\n BigInt(step.estimate.fromAmount),\n step.action.fromToken.decimals,\n );\n } else {\n fromAmount = formatTokenAmount(\n BigInt(step.estimate.fromAmount),\n step.action.fromToken.decimals,\n );\n }\n\n const showToAmount =\n step.type !== 'custom' && step.tool !== 'custom' && !sameTokenProtocolStep;\n\n return (\n \n {!showToAmount ? (\n <>\n {formatUnits(\n BigInt(step.estimate.fromAmount),\n step.action.fromToken.decimals,\n )}{' '}\n {step.action.fromToken.symbol}\n {' - '}\n \n ) : null}\n {t('format.number', {\n value: fromAmount,\n })}{' '}\n {step.action.fromToken.symbol}\n {showToAmount ? (\n <>\n \n {t('format.number', {\n value: formatTokenAmount(\n BigInt(step.execution?.toAmount ?? step.estimate.toAmount),\n step.execution?.toToken?.decimals ?? step.action.toToken.decimals,\n ),\n })}{' '}\n {step.execution?.toToken?.symbol ?? step.action.toToken.symbol}\n \n ) : (\n ` (${t('format.currency', {\n value:\n parseFloat(fromAmount) * parseFloat(step.action.fromToken.priceUSD),\n })})`\n )}\n \n );\n};\n\nexport const CustomStepDetailsLabel: React.FC = ({\n step,\n subvariant,\n subvariantOptions,\n}) => {\n const { t } = useTranslation();\n\n if (!subvariant) {\n return null;\n }\n\n // FIXME: step transaction request overrides step tool details, but not included step tool details\n const toolDetails =\n subvariant === 'custom' &&\n (step as unknown as LiFiStep).includedSteps?.length > 0\n ? (step as unknown as LiFiStep).includedSteps.find(\n (step) => step.tool === 'custom' && step.toolDetails.key !== 'custom',\n )?.toolDetails || step.toolDetails\n : step.toolDetails;\n\n const stepDetailsKey =\n (subvariant === 'custom' && subvariantOptions?.custom) || 'checkout';\n\n return (\n \n {t(`main.${stepDetailsKey}StepDetails`, {\n tool: toolDetails.name,\n })}\n \n );\n};\n\nexport const BridgeStepDetailsLabel: React.FC<\n Omit\n> = ({ step }) => {\n const { t } = useTranslation();\n const { getChainById } = useAvailableChains();\n return (\n \n {t('main.bridgeStepDetails', {\n from: getChainById(step.action.fromChainId)?.name,\n to: getChainById(step.action.toChainId)?.name,\n tool: step.toolDetails.name,\n })}\n \n );\n};\n\nexport const SwapStepDetailsLabel: React.FC<\n Omit\n> = ({ step }) => {\n const { t } = useTranslation();\n const { getChainById } = useAvailableChains();\n return (\n \n {t('main.swapStepDetails', {\n chain: getChainById(step.action.fromChainId)?.name,\n tool: step.toolDetails.name,\n })}\n \n );\n};\n\nexport const ProtocolStepDetailsLabel: React.FC<\n Omit\n> = ({ step, feeConfig }) => {\n const { t } = useTranslation();\n return (\n \n {step.toolDetails.key === 'feeCollection'\n ? feeConfig?.name\n ? t('main.fees.integrator', { tool: feeConfig.name })\n : t('main.fees.defaultIntegrator')\n : step.toolDetails.key === 'lifuelProtocol'\n ? t('main.refuelStepDetails', {\n tool: step.toolDetails.name,\n })\n : step.toolDetails.name}\n \n );\n};\n","import type { ObserverInstanceCallback } from \"./index\";\n\nconst observerMap = new Map<\n string,\n {\n id: string;\n observer: IntersectionObserver;\n elements: Map>;\n }\n>();\n\nconst RootIds: WeakMap = new WeakMap();\nlet rootId = 0;\n\nlet unsupportedValue: boolean | undefined = undefined;\n\n/**\n * What should be the default behavior if the IntersectionObserver is unsupported?\n * Ideally the polyfill has been loaded, you can have the following happen:\n * - `undefined`: Throw an error\n * - `true` or `false`: Set the `inView` value to this regardless of intersection state\n * **/\nexport function defaultFallbackInView(inView: boolean | undefined) {\n unsupportedValue = inView;\n}\n\n/**\n * Generate a unique ID for the root element\n * @param root\n */\nfunction getRootId(root: IntersectionObserverInit[\"root\"]) {\n if (!root) return \"0\";\n if (RootIds.has(root)) return RootIds.get(root);\n rootId += 1;\n RootIds.set(root, rootId.toString());\n return RootIds.get(root);\n}\n\n/**\n * Convert the options to a string Id, based on the values.\n * Ensures we can reuse the same observer when observing elements with the same options.\n * @param options\n */\nexport function optionsToId(options: IntersectionObserverInit) {\n return Object.keys(options)\n .sort()\n .filter(\n (key) => options[key as keyof IntersectionObserverInit] !== undefined,\n )\n .map((key) => {\n return `${key}_${\n key === \"root\"\n ? getRootId(options.root)\n : options[key as keyof IntersectionObserverInit]\n }`;\n })\n .toString();\n}\n\nfunction createObserver(options: IntersectionObserverInit) {\n // Create a unique ID for this observer instance, based on the root, root margin and threshold.\n const id = optionsToId(options);\n let instance = observerMap.get(id);\n\n if (!instance) {\n // Create a map of elements this observer is going to observe. Each element has a list of callbacks that should be triggered, once it comes into view.\n const elements = new Map>();\n // biome-ignore lint/style/useConst: It's fine to use let here, as we are going to assign it later\n let thresholds: number[] | readonly number[];\n\n const observer = new IntersectionObserver((entries) => {\n entries.forEach((entry) => {\n // While it would be nice if you could just look at isIntersecting to determine if the component is inside the viewport, browsers can't agree on how to use it.\n // -Firefox ignores `threshold` when considering `isIntersecting`, so it will never be false again if `threshold` is > 0\n const inView =\n entry.isIntersecting &&\n thresholds.some((threshold) => entry.intersectionRatio >= threshold);\n\n // @ts-ignore support IntersectionObserver v2\n if (options.trackVisibility && typeof entry.isVisible === \"undefined\") {\n // The browser doesn't support Intersection Observer v2, falling back to v1 behavior.\n // @ts-ignore\n entry.isVisible = inView;\n }\n\n elements.get(entry.target)?.forEach((callback) => {\n callback(inView, entry);\n });\n });\n }, options);\n\n // Ensure we have a valid thresholds array. If not, use the threshold from the options\n thresholds =\n observer.thresholds ||\n (Array.isArray(options.threshold)\n ? options.threshold\n : [options.threshold || 0]);\n\n instance = {\n id,\n observer,\n elements,\n };\n\n observerMap.set(id, instance);\n }\n\n return instance;\n}\n\n/**\n * @param element - DOM Element to observe\n * @param callback - Callback function to trigger when intersection status changes\n * @param options - Intersection Observer options\n * @param fallbackInView - Fallback inView value.\n * @return Function - Cleanup function that should be triggered to unregister the observer\n */\nexport function observe(\n element: Element,\n callback: ObserverInstanceCallback,\n options: IntersectionObserverInit = {},\n fallbackInView = unsupportedValue,\n) {\n if (\n typeof window.IntersectionObserver === \"undefined\" &&\n fallbackInView !== undefined\n ) {\n const bounds = element.getBoundingClientRect();\n callback(fallbackInView, {\n isIntersecting: fallbackInView,\n target: element,\n intersectionRatio:\n typeof options.threshold === \"number\" ? options.threshold : 0,\n time: 0,\n boundingClientRect: bounds,\n intersectionRect: bounds,\n rootBounds: bounds,\n });\n return () => {\n // Nothing to cleanup\n };\n }\n // An observer with the same options can be reused, so lets use this fact\n const { id, observer, elements } = createObserver(options);\n\n // Register the callback listener for this element\n const callbacks = elements.get(element) || [];\n if (!elements.has(element)) {\n elements.set(element, callbacks);\n }\n\n callbacks.push(callback);\n observer.observe(element);\n\n return function unobserve() {\n // Remove the callback from the callback list\n callbacks.splice(callbacks.indexOf(callback), 1);\n\n if (callbacks.length === 0) {\n // No more callback exists for element, so destroy it\n elements.delete(element);\n observer.unobserve(element);\n }\n\n if (elements.size === 0) {\n // No more elements are being observer by this instance, so destroy it\n observer.disconnect();\n observerMap.delete(id);\n }\n };\n}\n","import * as React from \"react\";\nimport type { IntersectionObserverProps, PlainChildrenProps } from \"./index\";\nimport { observe } from \"./observe\";\n\ntype State = {\n inView: boolean;\n entry?: IntersectionObserverEntry;\n};\n\nfunction isPlainChildren(\n props: IntersectionObserverProps | PlainChildrenProps,\n): props is PlainChildrenProps {\n return typeof props.children !== \"function\";\n}\n\n/**\n ## Render props\n\n To use the `` component, you pass it a function. It will be called\n whenever the state changes, with the new value of `inView`. In addition to the\n `inView` prop, children also receive a `ref` that should be set on the\n containing DOM element. This is the element that the IntersectionObserver will\n monitor.\n\n If you need it, you can also access the\n [`IntersectionObserverEntry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry)\n on `entry`, giving you access to all the details about the current intersection\n state.\n\n ```jsx\n import { InView } from 'react-intersection-observer';\n\n const Component = () => (\n \n {({ inView, ref, entry }) => (\n
\n

{`Header inside viewport ${inView}.`}

\n
\n )}\n
\n );\n\n export default Component;\n ```\n\n ## Plain children\n\n You can pass any element to the ``, and it will handle creating the\n wrapping DOM element. Add a handler to the `onChange` method, and control the\n state in your own component. Any extra props you add to `` will be\n passed to the HTML element, allowing you set the `className`, `style`, etc.\n\n ```jsx\n import { InView } from 'react-intersection-observer';\n\n const Component = () => (\n console.log('Inview:', inView)}>\n

Plain children are always rendered. Use onChange to monitor state.

\n
\n );\n\n export default Component;\n ```\n */\nexport class InView extends React.Component<\n IntersectionObserverProps | PlainChildrenProps,\n State\n> {\n node: Element | null = null;\n _unobserveCb: (() => void) | null = null;\n\n constructor(props: IntersectionObserverProps | PlainChildrenProps) {\n super(props);\n this.state = {\n inView: !!props.initialInView,\n entry: undefined,\n };\n }\n\n componentDidMount() {\n this.unobserve();\n this.observeNode();\n }\n\n componentDidUpdate(prevProps: IntersectionObserverProps) {\n // If a IntersectionObserver option changed, reinit the observer\n if (\n prevProps.rootMargin !== this.props.rootMargin ||\n prevProps.root !== this.props.root ||\n prevProps.threshold !== this.props.threshold ||\n prevProps.skip !== this.props.skip ||\n prevProps.trackVisibility !== this.props.trackVisibility ||\n prevProps.delay !== this.props.delay\n ) {\n this.unobserve();\n this.observeNode();\n }\n }\n\n componentWillUnmount() {\n this.unobserve();\n }\n\n observeNode() {\n if (!this.node || this.props.skip) return;\n const {\n threshold,\n root,\n rootMargin,\n trackVisibility,\n delay,\n fallbackInView,\n } = this.props;\n\n this._unobserveCb = observe(\n this.node,\n this.handleChange,\n {\n threshold,\n root,\n rootMargin,\n // @ts-ignore\n trackVisibility,\n // @ts-ignore\n delay,\n },\n fallbackInView,\n );\n }\n\n unobserve() {\n if (this._unobserveCb) {\n this._unobserveCb();\n this._unobserveCb = null;\n }\n }\n\n handleNode = (node?: Element | null) => {\n if (this.node) {\n // Clear the old observer, before we start observing a new element\n this.unobserve();\n\n if (!node && !this.props.triggerOnce && !this.props.skip) {\n // Reset the state if we get a new node, and we aren't ignoring updates\n this.setState({ inView: !!this.props.initialInView, entry: undefined });\n }\n }\n\n this.node = node ? node : null;\n this.observeNode();\n };\n\n handleChange = (inView: boolean, entry: IntersectionObserverEntry) => {\n if (inView && this.props.triggerOnce) {\n // If `triggerOnce` is true, we should stop observing the element.\n this.unobserve();\n }\n if (!isPlainChildren(this.props)) {\n // Store the current State, so we can pass it to the children in the next render update\n // There's no reason to update the state for plain children, since it's not used in the rendering.\n this.setState({ inView, entry });\n }\n if (this.props.onChange) {\n // If the user is actively listening for onChange, always trigger it\n this.props.onChange(inView, entry);\n }\n };\n\n render() {\n const { children } = this.props;\n if (typeof children === \"function\") {\n const { inView, entry } = this.state;\n return children({ inView, entry, ref: this.handleNode });\n }\n\n const {\n as,\n triggerOnce,\n threshold,\n root,\n rootMargin,\n onChange,\n skip,\n trackVisibility,\n delay,\n initialInView,\n fallbackInView,\n ...props\n } = this.props as PlainChildrenProps;\n\n return React.createElement(\n as || \"div\",\n { ref: this.handleNode, ...props },\n children,\n );\n }\n}\n","import { useTheme } from '@mui/material';\nimport type { PropsWithChildren } from 'react';\nimport { useCallback, useLayoutEffect, useRef, useState } from 'react';\nimport { useInView } from 'react-intersection-observer';\nimport type { TextFitterProps } from './types.js';\n\nconst initialState = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n};\n\nexport const TextFitter: React.FC> = ({\n children,\n width = '100%',\n height,\n maxHeight,\n preserveAspectRatio = 'xMinYMid meet',\n textStyle,\n svgStyle,\n cropTop,\n cropBottom,\n onFit,\n}) => {\n const theme = useTheme();\n const textRef = useRef(null);\n const [viewBox, setViewBox] = useState>(initialState);\n\n const [ref] = useInView({\n onChange(inView) {\n if (inView) {\n calculateBox();\n }\n },\n });\n\n const calculateBox = useCallback(() => {\n if (!textRef.current) {\n return;\n }\n const box = textRef.current.getBBox();\n if (cropTop) {\n box.y += box.height * cropTop;\n box.height -= box.height * cropTop;\n }\n if (cropBottom) {\n box.height -= box.height * cropBottom;\n }\n setViewBox(box);\n onFit?.();\n }, [cropBottom, cropTop, onFit]);\n\n useLayoutEffect(() => {\n calculateBox();\n }, [calculateBox, children]);\n\n useLayoutEffect(() => {\n if (document.fonts) {\n document.fonts.ready.then(() => {\n calculateBox();\n });\n }\n }, [calculateBox]);\n\n return (\n = maxHeight\n // ? maxHeight\n // : height\n // }\n preserveAspectRatio={preserveAspectRatio}\n fill={theme.palette.text.primary}\n ref={ref}\n >\n \n {children}\n \n \n );\n};\n","import * as React from \"react\";\nimport type { InViewHookResponse, IntersectionOptions } from \"./index\";\nimport { observe } from \"./observe\";\n\ntype State = {\n inView: boolean;\n entry?: IntersectionObserverEntry;\n};\n\n/**\n * React Hooks make it easy to monitor the `inView` state of your components. Call\n * the `useInView` hook with the (optional) [options](#options) you need. It will\n * return an array containing a `ref`, the `inView` status and the current\n * [`entry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry).\n * Assign the `ref` to the DOM element you want to monitor, and the hook will\n * report the status.\n *\n * @example\n * ```jsx\n * import React from 'react';\n * import { useInView } from 'react-intersection-observer';\n *\n * const Component = () => {\n * const { ref, inView, entry } = useInView({\n * threshold: 0,\n * });\n *\n * return (\n *
\n *

{`Header inside viewport ${inView}.`}

\n *
\n * );\n * };\n * ```\n */\nexport function useInView({\n threshold,\n delay,\n trackVisibility,\n rootMargin,\n root,\n triggerOnce,\n skip,\n initialInView,\n fallbackInView,\n onChange,\n}: IntersectionOptions = {}): InViewHookResponse {\n const [ref, setRef] = React.useState(null);\n const callback = React.useRef();\n const [state, setState] = React.useState({\n inView: !!initialInView,\n entry: undefined,\n });\n\n // Store the onChange callback in a `ref`, so we can access the latest instance\n // inside the `useEffect`, but without triggering a rerender.\n callback.current = onChange;\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: threshold is not correctly detected as a dependency\n React.useEffect(\n () => {\n // Ensure we have node ref, and that we shouldn't skip observing\n if (skip || !ref) return;\n\n let unobserve: (() => void) | undefined;\n unobserve = observe(\n ref,\n (inView, entry) => {\n setState({\n inView,\n entry,\n });\n if (callback.current) callback.current(inView, entry);\n\n if (entry.isIntersecting && triggerOnce && unobserve) {\n // If it should only trigger once, unobserve the element after it's inView\n unobserve();\n unobserve = undefined;\n }\n },\n {\n root,\n rootMargin,\n threshold,\n // @ts-ignore\n trackVisibility,\n // @ts-ignore\n delay,\n },\n fallbackInView,\n );\n\n return () => {\n if (unobserve) {\n unobserve();\n }\n };\n },\n // We break the rule here, because we aren't including the actual `threshold` variable\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n // If the threshold is an array, convert it to a string, so it won't change between renders.\n Array.isArray(threshold) ? threshold.toString() : threshold,\n ref,\n root,\n rootMargin,\n triggerOnce,\n skip,\n trackVisibility,\n fallbackInView,\n delay,\n ],\n );\n\n const entryTarget = state.entry?.target;\n const previousEntryTarget = React.useRef();\n if (\n !ref &&\n entryTarget &&\n !triggerOnce &&\n !skip &&\n previousEntryTarget.current !== entryTarget\n ) {\n // If we don't have a node ref, then reset the state (unless the hook is set to only `triggerOnce` or `skip`)\n // This ensures we correctly reflect the current state - If you aren't observing anything, then nothing is inView\n previousEntryTarget.current = entryTarget;\n setState({\n inView: !!initialInView,\n entry: undefined,\n });\n }\n\n const result = [setRef, state.inView, state.entry] as InViewHookResponse;\n\n // Support object destructuring, by adding the specific values.\n result.ref = result[0];\n result.inView = result[1];\n result.entry = result[2];\n\n return result;\n}\n","import { Box, Typography, alpha, styled } from '@mui/material';\n\nexport const TextSecondaryContainer = styled(Box)(() => ({\n display: 'flex',\n alignItems: 'center',\n flexWrap: 'wrap',\n flex: 1,\n}));\n\nexport const TextSecondary = styled(Typography, {\n shouldForwardProp: (prop: string) => !['dot'].includes(prop),\n})<{ dot?: boolean }>(({ theme, dot }) => ({\n fontSize: 12,\n lineHeight: 1,\n fontWeight: 500,\n color: dot\n ? alpha(theme.palette.text.secondary, 0.56)\n : theme.palette.text.secondary,\n whiteSpace: 'nowrap',\n}));\n\nexport const TokenDivider = styled(Box)(({ theme }) => ({\n height: 16,\n borderLeftWidth: 2,\n borderLeftStyle: 'solid',\n borderColor:\n theme.palette.mode === 'light'\n ? theme.palette.grey[300]\n : theme.palette.grey[800],\n}));\n","/* eslint-disable react/no-array-index-key */\nimport type { LiFiStep, TokenAmount } from '@lifi/sdk';\nimport type { BoxProps } from '@mui/material';\nimport { Box, Grow, Skeleton, Tooltip } from '@mui/material';\nimport type { FC, PropsWithChildren, ReactElement } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useChain } from '../../hooks/useChain.js';\nimport { useToken } from '../../hooks/useToken.js';\nimport { formatTokenAmount, formatTokenPrice } from '../../utils/format.js';\nimport { AvatarBadgedSkeleton } from '../Avatar/Avatar.js';\nimport { TokenAvatar } from '../Avatar/TokenAvatar.js';\nimport { SmallAvatar } from '../SmallAvatar.js';\nimport { TextFitter } from '../TextFitter/TextFitter.js';\nimport { TextSecondary, TextSecondaryContainer } from './Token.style.js';\n\ninterface TokenProps {\n token: TokenAmount;\n impactToken?: TokenAmount;\n enableImpactTokenTooltip?: boolean;\n step?: LiFiStep;\n stepVisible?: boolean;\n disableDescription?: boolean;\n isLoading?: boolean;\n}\n\nexport const Token: FC = ({ token, ...other }) => {\n if (!token.priceUSD || !token.logoURI) {\n return ;\n }\n return ;\n};\n\nexport const TokenFallback: FC = ({\n token,\n isLoading,\n ...other\n}) => {\n const { token: chainToken, isLoading: isLoadingToken } = useToken(\n token.chainId,\n token.address,\n );\n\n return (\n \n );\n};\n\nexport const TokenBase: FC = ({\n token,\n impactToken,\n enableImpactTokenTooltip,\n step,\n stepVisible,\n disableDescription,\n isLoading,\n ...other\n}) => {\n const { t, i18n } = useTranslation();\n const { chain } = useChain(token?.chainId);\n\n if (isLoading) {\n return (\n \n );\n }\n\n const tokenAmount = formatTokenAmount(token.amount, token.decimals);\n const tokenPrice = formatTokenPrice(tokenAmount, token.priceUSD);\n\n let priceImpact;\n let priceImpactPercent;\n if (impactToken) {\n const impactTokenAmount = formatTokenAmount(\n impactToken.amount,\n impactToken.decimals,\n );\n const impactTokenPrice =\n formatTokenPrice(impactTokenAmount, impactToken.priceUSD) || 0.01;\n\n priceImpact = tokenPrice / impactTokenPrice - 1;\n priceImpactPercent = priceImpact * 100;\n }\n\n const tokenOnChain = !disableDescription ? (\n \n {t(`main.tokenOnChain`, {\n tokenSymbol: token.symbol,\n chainName: chain?.name,\n })}\n \n ) : null;\n\n return (\n \n \n \n \n \n {t('format.number', {\n value: tokenAmount,\n })}\n \n \n \n \n {t(`format.currency`, {\n value: tokenPrice,\n })}\n \n {impactToken ? (\n \n •\n \n ) : null}\n {impactToken ? (\n enableImpactTokenTooltip ? (\n \n \n {t('format.percent', { value: priceImpact })}\n \n \n ) : (\n \n {t('format.percent', { value: priceImpact })}\n \n )\n ) : null}\n {!disableDescription ? (\n \n •\n \n ) : null}\n {step ? (\n \n {tokenOnChain}\n \n ) : (\n tokenOnChain\n )}\n \n \n \n );\n};\n\nconst TokenStep: FC>> = ({\n step,\n stepVisible,\n disableDescription,\n children,\n}) => {\n return (\n \n \n \n {children as ReactElement}\n \n \n \n \n \n \n {step?.toolDetails.name[0]}\n \n \n {step?.toolDetails.name}\n \n \n \n );\n};\n\nexport const TokenSkeleton: FC & BoxProps> = ({\n step,\n disableDescription,\n ...other\n}) => {\n return (\n \n \n \n \n \n \n \n {!step && !disableDescription ? (\n \n ) : null}\n \n \n \n \n );\n};\n","import { Box, styled } from '@mui/material';\n\nexport const TokenContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n height: 40,\n}));\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"m19.77 7.23.01-.01-3.19-3.19c-.29-.29-.77-.29-1.06 0-.29.29-.29.77 0 1.06l1.58 1.58c-1.05.4-1.76 1.47-1.58 2.71.16 1.1 1.1 1.99 2.2 2.11.47.05.88-.03 1.27-.2v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v15c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-6.5h1.5v4.86c0 1.31.94 2.5 2.24 2.63 1.5.15 2.76-1.02 2.76-2.49V9c0-.69-.28-1.32-.73-1.77M12 10H6V6c0-.55.45-1 1-1h4c.55 0 1 .45 1 1zm6 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1\"\n}), 'LocalGasStationRounded');","import { Box, Tooltip, Typography } from '@mui/material';\nimport type { TFunction } from 'i18next';\nimport type { ReactElement } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { formatUnits } from 'viem';\nimport type { FeesBreakdown } from '../utils/fees.js';\n\nexport interface FeeBreakdownTooltipProps {\n gasCosts?: FeesBreakdown[];\n feeCosts?: FeesBreakdown[];\n children: ReactElement;\n}\n\nexport const FeeBreakdownTooltip: React.FC = ({\n gasCosts,\n feeCosts,\n children,\n}) => {\n const { t } = useTranslation();\n return (\n \n {gasCosts?.length ? (\n \n {t('main.fees.network')}\n {getFeeBreakdownTypography(gasCosts, t)}\n \n ) : null}\n {feeCosts?.length ? (\n \n {t('main.fees.provider')}\n {getFeeBreakdownTypography(feeCosts, t)}\n \n ) : null}\n \n }\n sx={{ cursor: 'help' }}\n >\n {children}\n \n );\n};\n\nexport const getFeeBreakdownTypography = (\n fees: FeesBreakdown[],\n t: TFunction,\n) =>\n fees.map((fee, index) => (\n \n {t(`format.currency`, { value: fee.amountUSD })} (\n {parseFloat(formatUnits(fee.amount, fee.token.decimals))?.toFixed(9)}{' '}\n {fee.token.symbol})\n \n ));\n","import { createStore } from 'zustand/vanilla';\nexport * from 'zustand/vanilla';\nimport ReactExports from 'react';\nimport useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector.js';\n\nconst { useDebugValue } = ReactExports;\nconst { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports;\nlet didWarnAboutEqualityFn = false;\nconst identity = (arg) => arg;\nfunction useStore(api, selector = identity, equalityFn) {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && equalityFn && !didWarnAboutEqualityFn) {\n console.warn(\n \"[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937\"\n );\n didWarnAboutEqualityFn = true;\n }\n const slice = useSyncExternalStoreWithSelector(\n api.subscribe,\n api.getState,\n api.getServerState || api.getInitialState,\n selector,\n equalityFn\n );\n useDebugValue(slice);\n return slice;\n}\nconst createImpl = (createState) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && typeof createState !== \"function\") {\n console.warn(\n \"[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.\"\n );\n }\n const api = typeof createState === \"function\" ? createStore(createState) : createState;\n const useBoundStore = (selector, equalityFn) => useStore(api, selector, equalityFn);\n Object.assign(useBoundStore, api);\n return useBoundStore;\n};\nconst create = (createState) => createState ? createImpl(createState) : createImpl;\nvar react = (createState) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\n \"[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.\"\n );\n }\n return create(createState);\n};\n\nexport { create, react as default, useStore };\n","import { Typography, styled } from '@mui/material';\n\nexport const TokenRateTypography = styled(Typography)(({ theme }) => ({\n fontSize: 14,\n lineHeight: 1.429,\n fontWeight: 500,\n color: theme.palette.text.primary,\n cursor: 'pointer',\n '&:hover': {\n opacity: 1,\n },\n opacity: 0.56,\n transition: theme.transitions.create(['opacity'], {\n duration: theme.transitions.duration.enteringScreen,\n easing: theme.transitions.easing.easeOut,\n }),\n}));\n","import type { RouteExtended } from '@lifi/sdk';\nimport type { TypographyProps } from '@mui/material';\nimport type { MouseEventHandler } from 'react';\nimport { formatUnits } from 'viem';\nimport { create } from 'zustand';\nimport {\n convertToSubscriptFormat,\n precisionFormatter,\n} from '../../utils/format.js';\nimport { TokenRateTypography } from './TokenRate.style.js';\n\ninterface TokenRateProps extends TypographyProps {\n route: RouteExtended;\n}\n\ninterface TokenRateState {\n isForward: boolean;\n toggleIsForward(): void;\n}\n\nconst useTokenRateStore = create((set) => ({\n isForward: true,\n toggleIsForward: () => set((state) => ({ isForward: !state.isForward })),\n}));\n\nexport const TokenRate: React.FC = ({ route }) => {\n const { isForward, toggleIsForward } = useTokenRateStore();\n\n const toggleRate: MouseEventHandler = (e) => {\n e.stopPropagation();\n toggleIsForward();\n };\n\n const lastStep = route.steps.at(-1);\n\n const fromToken = {\n ...route.fromToken,\n amount: BigInt(route.fromAmount),\n };\n const toToken = {\n ...(lastStep?.execution?.toToken ??\n lastStep?.action.toToken ??\n route.toToken),\n amount: lastStep?.execution?.toAmount\n ? BigInt(lastStep.execution.toAmount)\n : BigInt(route.toAmount),\n };\n\n const fromToRate =\n parseFloat(formatUnits(toToken.amount!, toToken.decimals)) /\n parseFloat(formatUnits(fromToken.amount!, fromToken.decimals));\n const toFromRate =\n parseFloat(formatUnits(fromToken.amount!, fromToken.decimals)) /\n parseFloat(formatUnits(toToken.amount!, toToken.decimals));\n\n const rateText = isForward\n ? `1 ${fromToken.symbol} ≈ ${convertToSubscriptFormat(fromToRate)} ${toToken.symbol}`\n : `1 ${toToken.symbol} ≈ ${convertToSubscriptFormat(toFromRate)} ${fromToken.symbol}`;\n\n const rateTitle = isForward\n ? `1 ${fromToken.symbol} ≈ ${precisionFormatter.format(fromToRate)} ${toToken.symbol}`\n : `1 ${toToken.symbol} ≈ ${precisionFormatter.format(toFromRate)} ${fromToken.symbol}`;\n\n return (\n \n {rateText}\n \n );\n};\n","import { AccessTimeFilled, LocalGasStationRounded } from '@mui/icons-material';\nimport { Box, Tooltip, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { getAccumulatedFeeCostsBreakdown } from '../../utils/fees.js';\nimport { FeeBreakdownTooltip } from '../FeeBreakdownTooltip.js';\nimport { IconTypography } from '../IconTypography.js';\nimport { TokenRate } from '../TokenRate/TokenRate.js';\nimport type { RouteCardEssentialsProps } from './types.js';\n\nexport const RouteCardEssentials: React.FC = ({\n route,\n}) => {\n const { t, i18n } = useTranslation();\n const executionTimeSeconds = Math.floor(\n route.steps.reduce(\n (duration, step) => duration + step.estimate.executionDuration,\n 0,\n ),\n );\n const executionTimeMinutes = Math.floor(executionTimeSeconds / 60);\n const { gasCosts, feeCosts, combinedFeesUSD } =\n getAccumulatedFeeCostsBreakdown(route);\n return (\n \n \n \n \n \n \n \n \n \n {t(`format.currency`, {\n value: combinedFeesUSD,\n })}\n \n \n \n \n \n \n \n \n \n {(executionTimeSeconds < 60\n ? executionTimeSeconds\n : executionTimeMinutes\n ).toLocaleString(i18n.language, {\n style: 'unit',\n unit: executionTimeSeconds < 60 ? 'second' : 'minute',\n unitDisplay: 'narrow',\n })}\n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"m11.99 18.54-7.37-5.73L3 14.07l9 7 9-7-1.63-1.27zM12 16l7.36-5.73L21 9l-9-7-9 7 1.63 1.27z\"\n}), 'Layers');","import { Layers } from '@mui/icons-material';\nimport { Box, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { IconTypography } from '../IconTypography.js';\nimport type { RouteCardEssentialsProps } from './types.js';\n\nexport const RouteCardEssentialsExpanded: React.FC<\n RouteCardEssentialsProps\n> = ({ route }) => {\n const { t } = useTranslation();\n return (\n \n \n \n \n \n \n {route.steps.length}\n \n \n \n \n {t(`tooltip.numberOfSteps`)}\n \n \n \n );\n};\n","import type { TokenAmount } from '@lifi/sdk';\nimport { ExpandLess, ExpandMore } from '@mui/icons-material';\nimport { Box, Collapse } from '@mui/material';\nimport type { MouseEventHandler } from 'react';\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { CardProps } from '../Card/Card.js';\nimport { Card } from '../Card/Card.js';\nimport { CardIconButton } from '../Card/CardIconButton.js';\nimport { CardLabel, CardLabelTypography } from '../Card/CardLabel.js';\nimport { StepActions } from '../StepActions/StepActions.js';\nimport { Token } from '../Token/Token.js';\nimport { TokenContainer } from './RouteCard.style.js';\nimport { RouteCardEssentials } from './RouteCardEssentials.js';\nimport { RouteCardEssentialsExpanded } from './RouteCardEssentialsExpanded.js';\nimport type { RouteCardProps } from './types.js';\n\nexport const RouteCard: React.FC<\n RouteCardProps & Omit\n> = ({\n route,\n active,\n variant = 'default',\n expanded: defaulExpanded,\n ...other\n}) => {\n const { t } = useTranslation();\n const { subvariant } = useWidgetConfig();\n const [cardExpanded, setCardExpanded] = useState(defaulExpanded);\n\n const handleExpand: MouseEventHandler = (e) => {\n e.stopPropagation();\n setCardExpanded((expanded) => !expanded);\n };\n\n const token: TokenAmount =\n subvariant === 'custom'\n ? { ...route.fromToken, amount: BigInt(route.fromAmount) }\n : { ...route.toToken, amount: BigInt(route.toAmount) };\n const impactToken: TokenAmount | undefined =\n subvariant !== 'custom'\n ? { ...route.fromToken, amount: BigInt(route.fromAmount) }\n : undefined;\n\n const tags = route.tags?.filter(\n (tag) => tag === 'CHEAPEST' || tag === 'FASTEST',\n );\n\n const cardContent = (\n \n {subvariant !== 'refuel' && route.tags?.length ? (\n \n {tags?.length ? (\n \n \n {t(`main.tags.${tags[0].toLowerCase()}` as any)}\n \n \n ) : null}\n \n ) : null}\n \n \n {!defaulExpanded ? (\n \n {cardExpanded ? (\n \n ) : (\n \n )}\n \n ) : null}\n \n \n {route.steps.map((step) => (\n \n ))}\n \n \n \n \n );\n\n return subvariant === 'refuel' || variant === 'cardless' ? (\n cardContent\n ) : (\n \n {cardContent}\n \n );\n};\n","import { Box, Skeleton } from '@mui/material';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { CardProps } from '../Card/Card.js';\nimport { Card } from '../Card/Card.js';\nimport { TokenSkeleton } from '../Token/Token.js';\nimport type { RouteCardSkeletonProps } from './types.js';\n\nexport const RouteCardSkeleton: React.FC<\n RouteCardSkeletonProps & Omit\n> = ({ variant, ...other }) => {\n const { subvariant } = useWidgetConfig();\n\n const cardContent = (\n \n {subvariant !== 'refuel' && subvariant !== 'custom' ? (\n \n ({\n borderRadius: `${theme.shape.borderRadius}px`,\n })}\n />\n \n ) : null}\n \n \n \n \n \n \n );\n\n return subvariant === 'refuel' || variant === 'cardless' ? (\n cardContent\n ) : (\n \n {cardContent}\n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19 15.18V7c0-2.21-1.79-4-4-4s-4 1.79-4 4v10c0 1.1-.9 2-2 2s-2-.9-2-2V8.82C8.16 8.4 9 7.3 9 6c0-1.66-1.34-3-3-3S3 4.34 3 6c0 1.3.84 2.4 2 2.82V17c0 2.21 1.79 4 4 4s4-1.79 4-4V7c0-1.1.9-2 2-2s2 .9 2 2v8.18c-1.16.41-2 1.51-2 2.82 0 1.66 1.34 3 3 3s3-1.34 3-3c0-1.3-.84-2.4-2-2.82\"\n}), 'Route');","import { Route } from '@mui/icons-material';\nimport { Box, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nexport const RouteNotFoundCard: React.FC = () => {\n const { t } = useTranslation();\n return (\n \n \n \n \n \n {t('info.title.routeNotFound')}\n \n \n {t('info.message.routeNotFound')}\n \n \n );\n};\n","import { Box, Collapse } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { useRoutes } from '../../hooks/useRoutes.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { ButtonTertiary } from '../ButtonTertiary.js';\nimport type { CardProps } from '../Card/Card.js';\nimport { Card } from '../Card/Card.js';\nimport { CardTitle } from '../Card/CardTitle.js';\nimport { ProgressToNextUpdate } from '../ProgressToNextUpdate.js';\nimport { RouteCard } from '../RouteCard/RouteCard.js';\nimport { RouteCardSkeleton } from '../RouteCard/RouteCardSkeleton.js';\nimport { RouteNotFoundCard } from '../RouteCard/RouteNotFoundCard.js';\n\nexport const Routes: React.FC = (props) => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { subvariant, useRecommendedRoute } = useWidgetConfig();\n const {\n routes,\n isLoading,\n isFetching,\n isFetched,\n dataUpdatedAt,\n refetchTime,\n refetch,\n } = useRoutes();\n\n const currentRoute = routes?.[0];\n\n if (!currentRoute && !isLoading && !isFetching && !isFetched) {\n return null;\n }\n\n const handleCardClick = () => {\n navigate(navigationRoutes.routes);\n };\n\n const routeNotFound = !currentRoute && !isLoading && !isFetching;\n const onlyRecommendedRoute = subvariant === 'refuel' || useRecommendedRoute;\n const showAll =\n !onlyRecommendedRoute && !routeNotFound && (routes?.length ?? 0) > 1;\n\n return (\n \n \n {subvariant === 'custom' ? t('header.youPay') : t('header.receive')}\n \n refetch()}\n sx={{\n position: 'absolute',\n top: 8,\n right: 8,\n }}\n />\n \n {isLoading ? (\n \n ) : !currentRoute ? (\n \n ) : (\n \n )}\n\n \n \n \n {t('button.showAll')}\n \n \n \n \n \n );\n};\n","'use client';\n\nimport * as React from 'react';\nimport useEnhancedEffect from '@mui/utils/useEnhancedEffect';\nimport { getThemeProps } from '../useThemeProps';\nimport useTheme from '../useThemeWithoutDefault';\n\n/**\n * @deprecated Not used internally. Use `MediaQueryListEvent` from lib.dom.d.ts instead.\n */\n\n/**\n * @deprecated Not used internally. Use `MediaQueryList` from lib.dom.d.ts instead.\n */\n\n/**\n * @deprecated Not used internally. Use `(event: MediaQueryListEvent) => void` instead.\n */\n\nfunction useMediaQueryOld(query, defaultMatches, matchMedia, ssrMatchMedia, noSsr) {\n const [match, setMatch] = React.useState(() => {\n if (noSsr && matchMedia) {\n return matchMedia(query).matches;\n }\n if (ssrMatchMedia) {\n return ssrMatchMedia(query).matches;\n }\n\n // Once the component is mounted, we rely on the\n // event listeners to return the correct matches value.\n return defaultMatches;\n });\n useEnhancedEffect(() => {\n let active = true;\n if (!matchMedia) {\n return undefined;\n }\n const queryList = matchMedia(query);\n const updateMatch = () => {\n // Workaround Safari wrong implementation of matchMedia\n // TODO can we remove it?\n // https://github.com/mui/material-ui/pull/17315#issuecomment-528286677\n if (active) {\n setMatch(queryList.matches);\n }\n };\n updateMatch();\n // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n queryList.addListener(updateMatch);\n return () => {\n active = false;\n queryList.removeListener(updateMatch);\n };\n }, [query, matchMedia]);\n return match;\n}\n\n// eslint-disable-next-line no-useless-concat -- Workaround for https://github.com/webpack/webpack/issues/14814\nconst maybeReactUseSyncExternalStore = React['useSyncExternalStore' + ''];\nfunction useMediaQueryNew(query, defaultMatches, matchMedia, ssrMatchMedia, noSsr) {\n const getDefaultSnapshot = React.useCallback(() => defaultMatches, [defaultMatches]);\n const getServerSnapshot = React.useMemo(() => {\n if (noSsr && matchMedia) {\n return () => matchMedia(query).matches;\n }\n if (ssrMatchMedia !== null) {\n const {\n matches\n } = ssrMatchMedia(query);\n return () => matches;\n }\n return getDefaultSnapshot;\n }, [getDefaultSnapshot, query, ssrMatchMedia, noSsr, matchMedia]);\n const [getSnapshot, subscribe] = React.useMemo(() => {\n if (matchMedia === null) {\n return [getDefaultSnapshot, () => () => {}];\n }\n const mediaQueryList = matchMedia(query);\n return [() => mediaQueryList.matches, notify => {\n // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n mediaQueryList.addListener(notify);\n return () => {\n mediaQueryList.removeListener(notify);\n };\n }];\n }, [getDefaultSnapshot, matchMedia, query]);\n const match = maybeReactUseSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n return match;\n}\nexport default function useMediaQuery(queryInput, options = {}) {\n const theme = useTheme();\n // Wait for jsdom to support the match media feature.\n // All the browsers MUI support have this built-in.\n // This defensive check is here for simplicity.\n // Most of the time, the match media logic isn't central to people tests.\n const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined';\n const {\n defaultMatches = false,\n matchMedia = supportMatchMedia ? window.matchMedia : null,\n ssrMatchMedia = null,\n noSsr = false\n } = getThemeProps({\n name: 'MuiUseMediaQuery',\n props: options,\n theme\n });\n if (process.env.NODE_ENV !== 'production') {\n if (typeof queryInput === 'function' && theme === null) {\n console.error(['MUI: The `query` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.'].join('\\n'));\n }\n }\n let query = typeof queryInput === 'function' ? queryInput(theme) : queryInput;\n query = query.replace(/^@media( ?)/m, '');\n\n // TODO: Drop `useMediaQueryOld` and use `use-sync-external-store` shim in `useMediaQueryNew` once the package is stable\n const useMediaQueryImplementation = maybeReactUseSyncExternalStore !== undefined ? useMediaQueryNew : useMediaQueryOld;\n const match = useMediaQueryImplementation(query, defaultMatches, matchMedia, ssrMatchMedia, noSsr);\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue({\n query,\n match\n });\n }\n return match;\n}","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"m20 12-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8z\"\n}), 'ArrowDownward');","import { createContext, useContext, useRef } from 'react';\nimport { shallow } from 'zustand/shallow';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { PersistStoreProviderProps } from '../types.js';\nimport { createBookmarksStore } from './createBookmarkStore.js';\nimport type { BookmarkState, BookmarkStore } from './types.js';\n\nexport const BookmarkStoreContext = createContext(null);\n\nexport const BookmarkStoreProvider: React.FC = ({\n children,\n ...props\n}) => {\n const { toAddress } = useWidgetConfig();\n const storeRef = useRef();\n\n if (!storeRef.current) {\n storeRef.current = createBookmarksStore({ ...props, toAddress });\n }\n\n return (\n \n {children}\n \n );\n};\n\nexport function useBookmarkStore(\n selector: (store: BookmarkState) => T,\n equalityFunction = shallow,\n) {\n const useStore = useContext(BookmarkStoreContext);\n\n if (!useStore) {\n throw new Error(\n `You forgot to wrap your component in <${BookmarkStoreProvider.name}>.`,\n );\n }\n\n return useStore(selector, equalityFunction);\n}\n","import type { StateCreator } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport { createWithEqualityFn } from 'zustand/traditional';\nimport type { ToAddress } from '../../types/widget.js';\nimport type { PersistStoreProps } from '../types.js';\nimport type { BookmarkState } from './types.js';\n\nconst recentWalletsLimit = 10;\n\ninterface PersistBookmarkProps extends PersistStoreProps {\n toAddress?: ToAddress;\n}\nexport const createBookmarksStore = ({\n namePrefix,\n toAddress,\n}: PersistBookmarkProps) =>\n createWithEqualityFn(\n persist(\n (set, get) => ({\n selectedBookmark: toAddress,\n bookmarks: [],\n recentWallets: [],\n getBookmark: (address) =>\n get().bookmarks.find((bookmark) => bookmark.address === address),\n addBookmark: (bookmark) => {\n set((state) => ({\n bookmarks: [bookmark, ...state.bookmarks],\n }));\n },\n removeBookmark: (address) => {\n set((state) => ({\n bookmarks: state.bookmarks.filter(\n (storedBookmark) => storedBookmark.address !== address,\n ),\n }));\n },\n getSelectedBookmark: () => get().selectedBookmark,\n setSelectedBookmark: (bookmark) => {\n set((state) => ({\n selectedBookmark: bookmark,\n }));\n },\n addRecentWallet: (bookmark) => {\n set((state) => ({\n recentWallets: [\n bookmark,\n ...state.recentWallets.filter(\n (recentWallet) => recentWallet.address !== bookmark.address,\n ),\n ].slice(0, recentWalletsLimit),\n }));\n },\n removeRecentWallet: (address) => {\n set((state) => ({\n recentWallets: state.recentWallets.filter(\n (storedRecent) => storedRecent.address !== address,\n ),\n }));\n },\n }),\n {\n name: `${namePrefix || 'li.fi'}-bookmarks`,\n version: 0,\n partialize: (state) => ({\n bookmarks: state.bookmarks,\n recentWallets: state.recentWallets,\n }),\n onRehydrateStorage: () => {\n return (state) => {\n if (state && toAddress && !toAddress.name) {\n const existingBookmark = state.getBookmark(toAddress.address);\n if (existingBookmark) {\n state.setSelectedBookmark(existingBookmark);\n }\n }\n };\n },\n },\n ) as StateCreator,\n Object.is,\n );\n","import { shallow } from 'zustand/shallow';\nimport { useBookmarkStore } from './BookmarkStore.js';\nimport type { BookmarkActions } from './types.js';\n\nexport const useBookmarkActions = () => {\n const actions = useBookmarkStore(\n (store) => ({\n getBookmark: store.getBookmark,\n addBookmark: store.addBookmark,\n removeBookmark: store.removeBookmark,\n setSelectedBookmark: store.setSelectedBookmark,\n getSelectedBookmark: store.getSelectedBookmark,\n addRecentWallet: store.addRecentWallet,\n removeRecentWallet: store.removeRecentWallet,\n }),\n shallow,\n );\n\n return actions;\n};\n","import { shallow } from 'zustand/shallow';\nimport { useBookmarkStore } from './BookmarkStore.js';\nimport type { BookmarkProps } from './types.js';\n\nexport const useBookmarks = (): BookmarkProps => {\n const [bookmarks, selectedBookmark, recentWallets] = useBookmarkStore(\n (store) => [store.bookmarks, store.selectedBookmark, store.recentWallets],\n shallow,\n );\n\n return {\n bookmarks,\n selectedBookmark,\n recentWallets,\n };\n};\n","import type { ExtendedChain } from '@lifi/sdk';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { useBookmarkActions } from '../stores/bookmarks/useBookmarkActions.js';\nimport { useBookmarks } from '../stores/bookmarks/useBookmarks.js';\nimport { useFieldActions } from '../stores/form/useFieldActions.js';\nimport { RequiredUI } from '../types/widget.js';\n\nexport const useToAddressReset = () => {\n const { requiredUI } = useWidgetConfig();\n const { setFieldValue } = useFieldActions();\n const { selectedBookmark } = useBookmarks();\n const { setSelectedBookmark } = useBookmarkActions();\n\n const tryResetToAddress = (toChain: ExtendedChain) => {\n const requiredToAddress = requiredUI?.includes(RequiredUI.ToAddress);\n\n const bookmarkSatisfiesToChainType =\n selectedBookmark?.chainType === toChain?.chainType;\n\n const shouldResetToAddress =\n !requiredToAddress && !bookmarkSatisfiesToChainType;\n\n // toAddress field is required (always visible) when bridging between\n // two ecosystems (fromChain and toChain have different chain types).\n // We clean up toAddress on every chain change if toAddress is not required.\n // This is used when we switch between different chain ecosystems (chain types) and\n // prevents cases when after we switch the chain from one type to another \"Send to wallet\" field hides,\n // but it keeps toAddress value set for the previous chain pair.\n if (shouldResetToAddress) {\n setFieldValue('toAddress', '');\n setSelectedBookmark();\n }\n };\n\n return {\n tryResetToAddress,\n };\n};\n","import { Box, styled } from '@mui/material';\nimport { Card } from '../Card/Card.js';\n\nexport const IconCard = styled(Card)(({ theme }) => ({\n height: 32,\n width: 32,\n fontSize: 16,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n borderRadius: theme.shape.borderRadiusTertiary,\n zIndex: 1110,\n}));\n\nexport const ReverseContainer = styled(Box)(({ theme }) => {\n return {\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n margin: theme.spacing(-1),\n };\n});\n\nexport const ReverseTokensButtonEmpty = styled(Box)(({ theme }) => {\n return {\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n margin: theme.spacing(1),\n };\n});\n","import { ArrowDownward, ArrowForward } from '@mui/icons-material';\nimport { useAvailableChains } from '../../hooks/useAvailableChains.js';\nimport { useToAddressReset } from '../../hooks/useToAddressReset.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { IconCard, ReverseContainer } from './ReverseTokensButton.style.js';\n\nexport const ReverseTokensButton: React.FC<{ vertical?: boolean }> = ({\n vertical,\n}) => {\n const { setFieldValue, getFieldValues } = useFieldActions();\n const { getChainById } = useAvailableChains();\n const { tryResetToAddress } = useToAddressReset();\n\n const handleClick = () => {\n const [fromChainId, fromToken, toChainId, toToken] = getFieldValues(\n 'fromChain',\n 'fromToken',\n 'toChain',\n 'toToken',\n );\n setFieldValue('fromAmount', '', { isTouched: true });\n setFieldValue('fromChain', toChainId, { isTouched: true });\n setFieldValue('fromToken', toToken, { isTouched: true });\n setFieldValue('toChain', fromChainId, { isTouched: true });\n setFieldValue('toToken', fromToken, { isTouched: true });\n\n // fromChainId becomes toChainId after using reverse\n const toChain = getChainById(fromChainId);\n if (toChain) {\n tryResetToAddress(toChain);\n }\n };\n return (\n \n \n {vertical ? (\n \n ) : (\n \n )}\n \n \n );\n};\n","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getCardHeaderUtilityClass(slot) {\n return generateUtilityClass('MuiCardHeader', slot);\n}\nconst cardHeaderClasses = generateUtilityClasses('MuiCardHeader', ['root', 'avatar', 'action', 'content', 'title', 'subheader']);\nexport default cardHeaderClasses;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getCardContentUtilityClass(slot) {\n return generateUtilityClass('MuiCardContent', slot);\n}\nconst cardContentClasses = generateUtilityClasses('MuiCardContent', ['root']);\nexport default cardContentClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"className\", \"component\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport { getCardContentUtilityClass } from './cardContentClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root']\n };\n return composeClasses(slots, getCardContentUtilityClass, classes);\n};\nconst CardContentRoot = styled('div', {\n name: 'MuiCardContent',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})(() => {\n return {\n padding: 16,\n '&:last-child': {\n paddingBottom: 24\n }\n };\n});\nconst CardContent = /*#__PURE__*/React.forwardRef(function CardContent(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCardContent'\n });\n const {\n className,\n component = 'div'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n component\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(CardContentRoot, _extends({\n as: component,\n className: clsx(classes.root, className),\n ownerState: ownerState,\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? CardContent.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default CardContent;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"action\", \"avatar\", \"className\", \"component\", \"disableTypography\", \"subheader\", \"subheaderTypographyProps\", \"title\", \"titleTypographyProps\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport Typography from '../Typography';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport cardHeaderClasses, { getCardHeaderUtilityClass } from './cardHeaderClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root'],\n avatar: ['avatar'],\n action: ['action'],\n content: ['content'],\n title: ['title'],\n subheader: ['subheader']\n };\n return composeClasses(slots, getCardHeaderUtilityClass, classes);\n};\nconst CardHeaderRoot = styled('div', {\n name: 'MuiCardHeader',\n slot: 'Root',\n overridesResolver: (props, styles) => _extends({\n [`& .${cardHeaderClasses.title}`]: styles.title,\n [`& .${cardHeaderClasses.subheader}`]: styles.subheader\n }, styles.root)\n})({\n display: 'flex',\n alignItems: 'center',\n padding: 16\n});\nconst CardHeaderAvatar = styled('div', {\n name: 'MuiCardHeader',\n slot: 'Avatar',\n overridesResolver: (props, styles) => styles.avatar\n})({\n display: 'flex',\n flex: '0 0 auto',\n marginRight: 16\n});\nconst CardHeaderAction = styled('div', {\n name: 'MuiCardHeader',\n slot: 'Action',\n overridesResolver: (props, styles) => styles.action\n})({\n flex: '0 0 auto',\n alignSelf: 'flex-start',\n marginTop: -4,\n marginRight: -8,\n marginBottom: -4\n});\nconst CardHeaderContent = styled('div', {\n name: 'MuiCardHeader',\n slot: 'Content',\n overridesResolver: (props, styles) => styles.content\n})({\n flex: '1 1 auto'\n});\nconst CardHeader = /*#__PURE__*/React.forwardRef(function CardHeader(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCardHeader'\n });\n const {\n action,\n avatar,\n className,\n component = 'div',\n disableTypography = false,\n subheader: subheaderProp,\n subheaderTypographyProps,\n title: titleProp,\n titleTypographyProps\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n component,\n disableTypography\n });\n const classes = useUtilityClasses(ownerState);\n let title = titleProp;\n if (title != null && title.type !== Typography && !disableTypography) {\n title = /*#__PURE__*/_jsx(Typography, _extends({\n variant: avatar ? 'body2' : 'h5',\n className: classes.title,\n component: \"span\",\n display: \"block\"\n }, titleTypographyProps, {\n children: title\n }));\n }\n let subheader = subheaderProp;\n if (subheader != null && subheader.type !== Typography && !disableTypography) {\n subheader = /*#__PURE__*/_jsx(Typography, _extends({\n variant: avatar ? 'body2' : 'body1',\n className: classes.subheader,\n color: \"text.secondary\",\n component: \"span\",\n display: \"block\"\n }, subheaderTypographyProps, {\n children: subheader\n }));\n }\n return /*#__PURE__*/_jsxs(CardHeaderRoot, _extends({\n className: clsx(classes.root, className),\n as: component,\n ref: ref,\n ownerState: ownerState\n }, other, {\n children: [avatar && /*#__PURE__*/_jsx(CardHeaderAvatar, {\n className: classes.avatar,\n ownerState: ownerState,\n children: avatar\n }), /*#__PURE__*/_jsxs(CardHeaderContent, {\n className: classes.content,\n ownerState: ownerState,\n children: [title, subheader]\n }), action && /*#__PURE__*/_jsx(CardHeaderAction, {\n className: classes.action,\n ownerState: ownerState,\n children: action\n })]\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? CardHeader.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The action to display in the card header.\n */\n action: PropTypes.node,\n /**\n * The Avatar element to display.\n */\n avatar: PropTypes.node,\n /**\n * @ignore\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, `subheader` and `title` won't be wrapped by a Typography component.\n * This can be useful to render an alternative Typography variant by wrapping\n * the `title` text, and optional `subheader` text\n * with the Typography component.\n * @default false\n */\n disableTypography: PropTypes.bool,\n /**\n * The content of the component.\n */\n subheader: PropTypes.node,\n /**\n * These props will be forwarded to the subheader\n * (as long as disableTypography is not `true`).\n */\n subheaderTypographyProps: PropTypes.object,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The content of the component.\n */\n title: PropTypes.node,\n /**\n * These props will be forwarded to the title\n * (as long as disableTypography is not `true`).\n */\n titleTypographyProps: PropTypes.object\n} : void 0;\nexport default CardHeader;","import {\n CardHeader as MuiCardHeader,\n cardHeaderClasses,\n styled,\n} from '@mui/material';\n\nexport const CardHeader = styled(MuiCardHeader)(({ theme }) => ({\n [`.${cardHeaderClasses.action}`]: {\n marginTop: -2,\n alignSelf: 'center',\n },\n [`.${cardHeaderClasses.title}`]: {\n fontWeight: 600,\n fontSize: 18,\n lineHeight: 1.3334,\n color: theme.palette.text.primary,\n textAlign: 'left',\n },\n [`.${cardHeaderClasses.subheader}`]: {\n fontWeight: 500,\n fontSize: 12,\n lineHeight: 1.3334,\n color: theme.palette.text.secondary,\n textAlign: 'left',\n },\n}));\n","import {\n CardContent as MuiCardContent,\n cardHeaderClasses,\n darken,\n lighten,\n styled,\n} from '@mui/material';\nimport type { FormType } from '../../stores/form/types.js';\nimport { Card } from '../Card/Card.js';\nimport { CardHeader } from '../Card/CardHeader.js';\n\nexport const SelectTokenCardHeader = styled(CardHeader, {\n shouldForwardProp: (prop) =>\n !['selected', 'compact'].includes(prop as string),\n})<{ selected?: boolean; compact?: boolean }>(\n ({ theme, selected, compact }) => ({\n padding: theme.spacing(2),\n [`.${cardHeaderClasses.title}`]: {\n color: selected\n ? theme.palette.text.primary\n : theme.palette.text.secondary,\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n width: compact ? 96 : 256,\n fontSize: compact && !selected ? 16 : 18,\n fontWeight: selected ? 600 : 500,\n [theme.breakpoints.down(theme.breakpoints.values.sm)]: {\n width: compact ? 96 : 224,\n },\n },\n [`.${cardHeaderClasses.subheader}`]: {\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n width: compact ? 96 : 256,\n [theme.breakpoints.down(theme.breakpoints.values.sm)]: {\n width: compact ? 96 : 224,\n },\n },\n }),\n);\n\nexport const SelectTokenCard = styled(Card)(({ theme }) => {\n const cardVariant = theme.components?.MuiCard?.defaultProps?.variant;\n return {\n flex: 1,\n ...(cardVariant !== 'outlined' && {\n background: 'none',\n '&:hover': {\n cursor: 'pointer',\n background: 'none',\n },\n }),\n };\n});\n\nexport const CardContent = styled(MuiCardContent, {\n shouldForwardProp: (prop) => prop !== 'formType' && prop !== 'compact',\n})<{ formType: FormType; compact: boolean }>(({ theme, formType, compact }) => {\n const cardVariant = theme.components?.MuiCard?.defaultProps?.variant;\n const direction = formType === 'to' ? '-8px' : 'calc(100% + 8px)';\n const horizontal = compact ? direction : '50%';\n const vertical = compact ? '50%' : direction;\n return {\n padding: 0,\n transition: theme.transitions.create(['background-color'], {\n duration: theme.transitions.duration.enteringScreen,\n easing: theme.transitions.easing.easeOut,\n }),\n '&:last-child': {\n paddingBottom: 0,\n },\n ...(cardVariant !== 'outlined' && {\n backgroundColor: theme.palette.background.paper,\n mask: `radial-gradient(circle 20px at ${horizontal} ${vertical}, #fff0 96%, #fff) 100% 100% / 100% 100% no-repeat`,\n }),\n ...(cardVariant === 'filled' && {\n '&:hover': {\n cursor: 'pointer',\n backgroundColor:\n theme.palette.mode === 'light'\n ? darken(theme.palette.background.paper, 0.02)\n : lighten(theme.palette.background.paper, 0.02),\n },\n }),\n };\n});\n","import { Skeleton } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { useChain } from '../../hooks/useChain.js';\nimport { useSwapOnly } from '../../hooks/useSwapOnly.js';\nimport { useToken } from '../../hooks/useToken.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { FormTypeProps } from '../../stores/form/types.js';\nimport { FormKeyHelper } from '../../stores/form/types.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { AvatarBadgedDefault, AvatarBadgedSkeleton } from '../Avatar/Avatar.js';\nimport { TokenAvatar } from '../Avatar/TokenAvatar.js';\nimport { CardTitle } from '../Card/CardTitle.js';\nimport {\n CardContent,\n SelectTokenCard,\n SelectTokenCardHeader,\n} from './SelectTokenButton.style.js';\n\nexport const SelectTokenButton: React.FC<\n FormTypeProps & {\n compact: boolean;\n }\n> = ({ formType, compact }) => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { disabledUI, subvariant } = useWidgetConfig();\n const swapOnly = useSwapOnly();\n const tokenKey = FormKeyHelper.getTokenKey(formType);\n const [chainId, tokenAddress] = useFieldValues(\n FormKeyHelper.getChainKey(formType),\n tokenKey,\n );\n const { chain, isLoading: isChainLoading } = useChain(chainId);\n const { token, isLoading: isTokenLoading } = useToken(chainId, tokenAddress);\n\n const handleClick = () => {\n navigate(\n formType === 'from'\n ? navigationRoutes.fromToken\n : subvariant === 'refuel'\n ? navigationRoutes.toTokenNative\n : navigationRoutes.toToken,\n );\n };\n\n const isSelected = !!(chain && token);\n const onClick = !disabledUI?.includes(tokenKey) ? handleClick : undefined;\n const defaultPlaceholder =\n formType === 'to' && subvariant === 'refuel'\n ? t('main.selectChain')\n : formType === 'to' && swapOnly\n ? t('main.selectToken')\n : t('main.selectChainAndToken');\n const cardTitle: string =\n formType === 'from' && subvariant === 'custom'\n ? t(`header.payWith`)\n : t(`main.${formType}`);\n return (\n \n \n {cardTitle}\n {chainId && tokenAddress && (isChainLoading || isTokenLoading) ? (\n }\n title={}\n subheader={}\n compact={compact}\n />\n ) : (\n \n ) : (\n \n )\n }\n title={isSelected ? token.symbol : defaultPlaceholder}\n titleTypographyProps={{\n title: isSelected ? token.symbol : defaultPlaceholder,\n }}\n subheader={isSelected ? chain.name : null}\n subheaderTypographyProps={\n isSelected\n ? {\n title: chain.name,\n }\n : undefined\n }\n selected={isSelected}\n compact={compact}\n />\n )}\n \n \n );\n};\n","import type { BoxProps, Theme } from '@mui/material';\nimport { Box, useMediaQuery } from '@mui/material';\nimport { ReverseTokensButton } from '../components/ReverseTokensButton/ReverseTokensButton.js';\nimport { SelectTokenButton } from '../components/SelectTokenButton/SelectTokenButton.js';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldValues } from '../stores/form/useFieldValues.js';\nimport { DisabledUI, HiddenUI } from '../types/widget.js';\nimport { ReverseTokensButtonEmpty } from './ReverseTokensButton/ReverseTokensButton.style.js';\n\nexport const SelectChainAndToken: React.FC = (props) => {\n const prefersNarrowView = useMediaQuery((theme: Theme) =>\n theme.breakpoints.down('sm'),\n );\n const { disabledUI, hiddenUI, subvariant } = useWidgetConfig();\n\n const [fromChain, toChain, fromToken, toToken] = useFieldValues(\n 'fromChain',\n 'toChain',\n 'fromToken',\n 'toToken',\n );\n\n const hiddenReverse =\n subvariant === 'refuel' ||\n disabledUI?.includes(DisabledUI.FromToken) ||\n disabledUI?.includes(DisabledUI.ToToken) ||\n hiddenUI?.includes(HiddenUI.ToToken);\n\n const hiddenToToken =\n subvariant === 'custom' || hiddenUI?.includes(HiddenUI.ToToken);\n\n const isCompact =\n !!fromChain &&\n !!toChain &&\n !!fromToken &&\n !!toToken &&\n !prefersNarrowView &&\n !hiddenToToken;\n\n return (\n \n \n {!hiddenToToken ? (\n !hiddenReverse ? (\n \n ) : (\n \n )\n ) : null}\n {!hiddenToToken ? (\n \n ) : null}\n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M18.3 5.71a.9959.9959 0 0 0-1.41 0L12 10.59 7.11 5.7a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L10.59 12 5.7 16.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L12 13.41l4.89 4.89c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L13.41 12l4.89-4.89c.38-.38.38-1.02 0-1.4\"\n}), 'CloseRounded');","import { useChain } from '../hooks/useChain.js';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldValues } from '../stores/form/useFieldValues.js';\nimport { RequiredUI } from '../types/widget.js';\n\nexport const useToAddressRequirements = () => {\n const { requiredUI } = useWidgetConfig();\n const [fromChainId, toChainId] = useFieldValues('fromChain', 'toChain');\n\n const { chain: fromChain } = useChain(fromChainId);\n const { chain: toChain } = useChain(toChainId);\n\n const isDifferentChainType =\n fromChain && toChain && fromChain.chainType !== toChain.chainType;\n\n const requiredToAddress =\n requiredUI?.includes(RequiredUI.ToAddress) || isDifferentChainType;\n\n return {\n requiredToAddress,\n requiredToChainType: toChain?.chainType,\n };\n};\n","import { shallow } from 'zustand/shallow';\nimport { createWithEqualityFn } from 'zustand/traditional';\nimport type { SendToWalletStore } from './types.js';\n\nexport const useSendToWalletStore = createWithEqualityFn(\n (set) => ({\n showSendToWallet: false,\n setSendToWallet: (value) =>\n set({\n showSendToWallet: value,\n }),\n }),\n Object.is,\n);\n\nexport const useSendToWalletActions = () => {\n const actions = useSendToWalletStore(\n (store) => ({\n setSendToWallet: store.setSendToWallet,\n }),\n shallow,\n );\n\n return actions;\n};\n","export const shortenAddress = (address?: string) =>\n address\n ? `${address.substring(0, 5)}...${address.substring(address.length - 4)}`\n : null;\n",null,null,"\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M18 4H6C3.79 4 2 5.79 2 8v8c0 2.21 1.79 4 4 4h12c2.21 0 4-1.79 4-4V8c0-2.21-1.79-4-4-4m-1.86 9.77c-.24.2-.57.28-.88.2L4.15 11.25C4.45 10.52 5.16 10 6 10h12c.67 0 1.26.34 1.63.84zM6 6h12c1.1 0 2 .9 2 2v.55c-.59-.34-1.27-.55-2-.55H6c-.73 0-1.41.21-2 .55V8c0-1.1.9-2 2-2\"\n}), 'Wallet');","import { getConnectorIcon } from '@lifi/wallet-management';\nimport { Wallet } from '@mui/icons-material';\nimport { Badge } from '@mui/material';\nimport type { Account } from '../../hooks/useAccount.js';\nimport { useChain } from '../../hooks/useChain.js';\nimport type { ToAddress } from '../../types/widget.js';\nimport { SmallAvatar } from '../SmallAvatar.js';\nimport {\n AvatarDefault,\n AvatarDefaultBadge,\n AvatarMasked,\n} from './Avatar.style.js';\n\ninterface AccountAvatarProps {\n chainId?: number;\n account?: Account;\n toAddress?: ToAddress;\n empty?: boolean;\n}\n\nexport const AccountAvatar = ({\n chainId,\n account,\n empty,\n toAddress,\n}: AccountAvatarProps) => {\n const { chain } = useChain(chainId);\n\n const avatar = empty ? (\n \n ) : account?.connector || toAddress?.logoURI ? (\n \n {(toAddress?.name || account?.connector?.name)?.[0]}\n \n ) : (\n \n \n \n );\n\n return (\n \n {chain.name[0]}\n \n ) : (\n \n )\n }\n >\n {avatar}\n \n );\n};\n","import { cardHeaderClasses, styled } from '@mui/material';\nimport { CardHeader } from '../Card/CardHeader.js';\n\nexport const SendToWalletCardHeader = styled(CardHeader, {\n shouldForwardProp: (prop) => !['selected'].includes(prop as string),\n})<{ selected?: boolean }>(({ theme, selected }) => ({\n width: '100%',\n [`.${cardHeaderClasses.title}`]: {\n color: selected ? theme.palette.text.primary : theme.palette.text.secondary,\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n fontWeight: selected ? 600 : 500,\n width: selected ? 224 : 254,\n [theme.breakpoints.down(theme.breakpoints.values.sm)]: {\n width: selected ? 192 : 224,\n },\n },\n [`.${cardHeaderClasses.subheader}`]: {\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n width: selected ? 224 : 254,\n [theme.breakpoints.down(theme.breakpoints.values.sm)]: {\n width: selected ? 192 : 224,\n },\n },\n [`.${cardHeaderClasses.action}`]: {\n marginRight: 0,\n },\n [`.${cardHeaderClasses.action} > button`]: {\n fontSize: 16,\n },\n}));\n","import { CloseRounded } from '@mui/icons-material';\nimport { Box, Collapse } from '@mui/material';\nimport { useEffect, useRef, type MouseEventHandler } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useBookmarks } from '../../stores/bookmarks/useBookmarks.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { useSendToWalletStore } from '../../stores/settings/useSendToWalletStore.js';\nimport { DisabledUI, HiddenUI } from '../../types/widget.js';\nimport {\n defaultChainIdsByType,\n getChainTypeFromAddress,\n} from '../../utils/chainType.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { AccountAvatar } from '../Avatar/AccountAvatar.js';\nimport type { CardProps } from '../Card/Card.js';\nimport { Card } from '../Card/Card.js';\nimport { CardIconButton } from '../Card/CardIconButton.js';\nimport { CardTitle } from '../Card/CardTitle.js';\nimport { SendToWalletCardHeader } from './SendToWallet.style.js';\n\nexport const SendToWalletButton: React.FC = (props) => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { disabledUI, hiddenUI, toAddress, toAddresses } = useWidgetConfig();\n const { showSendToWallet } = useSendToWalletStore();\n const [toAddressFieldValue, toChainId, toTokenAddress] = useFieldValues(\n 'toAddress',\n 'toChain',\n 'toToken',\n );\n const { setFieldValue } = useFieldActions();\n const { selectedBookmark } = useBookmarks();\n const { setSelectedBookmark } = useBookmarkActions();\n const { accounts } = useAccount();\n const { requiredToAddress } = useToAddressRequirements();\n const disabledToAddress = disabledUI?.includes(DisabledUI.ToAddress);\n const hiddenToAddress = hiddenUI?.includes(HiddenUI.ToAddress);\n\n const address = toAddressFieldValue\n ? shortenAddress(toAddressFieldValue)\n : t('sendToWallet.enterAddress', {\n context: 'short',\n });\n\n const matchingConnectedAccount = accounts.find(\n (account) => account.address === toAddressFieldValue,\n );\n\n const chainType = !matchingConnectedAccount\n ? selectedBookmark?.chainType ||\n (toAddressFieldValue\n ? getChainTypeFromAddress(toAddressFieldValue)\n : undefined)\n : undefined;\n\n const chainId =\n toChainId && toTokenAddress\n ? toChainId\n : matchingConnectedAccount\n ? matchingConnectedAccount.chainId\n : chainType\n ? defaultChainIdsByType[chainType]\n : undefined;\n\n const isConnectedAccount =\n selectedBookmark?.isConnectedAccount &&\n matchingConnectedAccount?.isConnected;\n const connectedAccountName = matchingConnectedAccount?.connector?.name;\n const bookmarkName = selectedBookmark?.name;\n\n const headerTitle = isConnectedAccount\n ? connectedAccountName || address\n : bookmarkName || connectedAccountName || address;\n\n const headerSubheader =\n isConnectedAccount || bookmarkName || connectedAccountName ? address : null;\n\n const disabledForChanges = Boolean(toAddressFieldValue) && disabledToAddress;\n\n const handleOnClick = () => {\n navigate(\n toAddresses?.length\n ? navigationRoutes.configuredWallets\n : navigationRoutes.sendToWallet,\n );\n };\n\n const clearSelectedBookmark: MouseEventHandler = (e) => {\n e.stopPropagation();\n setFieldValue('toAddress', '', { isTouched: true });\n setSelectedBookmark();\n };\n\n // The collapse opens instantly on first page load/component mount when there is an address to display\n // After which it needs an animated transition for open and closing.\n // collapseTransitionTime is used specify the transition time for opening and closing\n const collapseTransitionTime = useRef(0);\n\n useEffect(() => {\n // timeout is needed here to push the collapseTransitionTime update to the back of the event loop\n // so that it doesn't fired too quickly\n setTimeout(() => {\n collapseTransitionTime.current = 225;\n }, 0);\n }, [collapseTransitionTime]);\n\n const isOpenCollapse =\n requiredToAddress || (showSendToWallet && !hiddenToAddress);\n\n return (\n \n \n \n {t('header.sendToWallet')}\n \n \n \n }\n title={headerTitle}\n subheader={headerSubheader}\n selected={!!toAddressFieldValue || disabledToAddress}\n action={\n !!toAddressFieldValue && !disabledForChanges ? (\n \n \n \n ) : null\n }\n />\n \n \n \n );\n};\n","import { Wallet } from '@mui/icons-material';\nimport { Button, Tooltip } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { useSendToWalletStore } from '../../stores/settings/useSendToWalletStore.js';\nimport { WidgetEvent } from '../../types/events.js';\nimport { DisabledUI, HiddenUI } from '../../types/widget.js';\n\nexport const SendToWalletExpandButton: React.FC = () => {\n const { t } = useTranslation();\n const { disabledUI, hiddenUI } = useWidgetConfig();\n const { setFieldValue } = useFieldActions();\n const { setSelectedBookmark } = useBookmarkActions();\n const emitter = useWidgetEvents();\n const { showSendToWallet, setSendToWallet } = useSendToWalletStore();\n const [toAddressFieldValue] = useFieldValues('toAddress');\n const { requiredToAddress } = useToAddressRequirements();\n\n if (requiredToAddress || hiddenUI?.includes(HiddenUI.ToAddress)) {\n return null;\n }\n\n const handleClick = () => {\n if (showSendToWallet && !disabledUI?.includes(DisabledUI.ToAddress)) {\n setFieldValue('toAddress', '', { isTouched: true });\n setSelectedBookmark();\n }\n setSendToWallet(!showSendToWallet);\n emitter.emit(\n WidgetEvent.SendToWalletToggled,\n useSendToWalletStore.getState().showSendToWallet,\n );\n };\n\n const buttonVariant =\n showSendToWallet || Boolean(toAddressFieldValue) ? 'contained' : 'text';\n\n return (\n \n \n \n \n \n );\n};\n","import type { Theme } from '@mui/material';\nimport { useMediaQuery } from '@mui/material';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\n\nconst defaultExpandableWidth = 852;\n\nexport const useWideVariant = () => {\n const { variant, useRecommendedRoute } = useWidgetConfig();\n const expandableAllowed = useMediaQuery((theme: Theme) =>\n theme.breakpoints.up(defaultExpandableWidth),\n );\n return variant === 'wide' && expandableAllowed && !useRecommendedRoute;\n};\n","import type { RouteExtended } from '@lifi/sdk';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { parseUnits } from 'viem';\nimport { useFieldValues } from '../stores/form/useFieldValues.js';\nimport { isRouteDone } from '../stores/routes/utils.js';\nimport { useAccount } from './useAccount.js';\nimport { useTokenAddressBalance } from './useTokenAddressBalance.js';\nimport { getTokenBalancesWithRetry } from './useTokenBalance.js';\n\nconst refetchInterval = 30_000;\n\nexport const useFromTokenSufficiency = (route?: RouteExtended) => {\n const [fromChainId, fromTokenAddress, fromAmount] = useFieldValues(\n 'fromChain',\n 'fromToken',\n 'fromAmount',\n );\n\n let chainId = fromChainId;\n let tokenAddress = fromTokenAddress;\n if (route) {\n chainId = route.fromToken.chainId;\n tokenAddress = route.fromToken.address;\n }\n\n const {\n token,\n chain,\n isLoading: isTokenAddressBalanceLoading,\n } = useTokenAddressBalance(chainId, tokenAddress);\n\n const { account } = useAccount({ chainType: chain?.chainType });\n\n const { data: insufficientFromToken, isLoading } = useQuery({\n queryKey: [\n 'from-token-sufficiency-check',\n account.address,\n chainId,\n tokenAddress,\n route?.id ?? fromAmount,\n ] as const,\n queryFn: async ({ queryKey: [, accountAddress] }) => {\n if (!accountAddress || !token) {\n return;\n }\n const parsedFromAmount = parseUnits(fromAmount, token.decimals);\n let currentTokenBalance = token.amount ?? 0n;\n\n if (!route || isRouteDone(route)) {\n const insufficientFunds = currentTokenBalance < parsedFromAmount;\n return insufficientFunds;\n }\n\n const currentAction = route.steps.filter(\n (step) => !step.execution || step.execution.status !== 'DONE',\n )[0]?.action;\n\n if (\n token.chainId === currentAction.fromToken.chainId &&\n token.address === currentAction.fromToken.address &&\n currentTokenBalance > 0\n ) {\n const insufficientFunds =\n BigInt(route.fromAmount) > currentTokenBalance;\n return insufficientFunds;\n }\n\n const tokenBalances = await getTokenBalancesWithRetry(accountAddress, [\n currentAction.fromToken,\n ]);\n\n currentTokenBalance = tokenBalances?.[0]?.amount ?? 0n;\n const insufficientFunds =\n BigInt(currentAction.fromAmount) > currentTokenBalance;\n return insufficientFunds;\n },\n\n enabled: Boolean(account.address && token && !isTokenAddressBalanceLoading),\n refetchInterval,\n staleTime: refetchInterval,\n placeholderData: keepPreviousData,\n });\n\n return {\n insufficientFromToken,\n isLoading,\n };\n};\n","import { type EVMChain, type RouteExtended, type Token } from '@lifi/sdk';\nimport { useQuery } from '@tanstack/react-query';\nimport type { Connector } from 'wagmi';\nimport { useAccount } from './useAccount.js';\nimport { useAvailableChains } from './useAvailableChains.js';\nimport { getTokenBalancesWithRetry } from './useTokenBalance.js';\n\nexport interface GasSufficiency {\n gasAmount: bigint;\n tokenAmount?: bigint;\n insufficientAmount?: bigint;\n insufficient?: boolean;\n token: Token;\n chain?: EVMChain;\n}\n\nconst refetchInterval = 30_000;\n\nexport const useGasSufficiency = (route?: RouteExtended) => {\n const { getChainById } = useAvailableChains();\n const { account } = useAccount({\n chainType: getChainById(route?.fromChainId)?.chainType,\n });\n\n const { data: insufficientGas, isLoading } = useQuery({\n queryKey: ['gas-sufficiency-check', account.address, route?.id],\n queryFn: async ({ queryKey: [, accountAddress] }) => {\n // We assume that LI.Fuel protocol always refuels the destination chain\n const hasRefuelStep = route!.steps\n .flatMap((step) => step.includedSteps)\n .some((includedStep) => includedStep.tool === 'lifuelProtocol');\n\n const gasCosts = route!.steps\n .filter((step) => !step.execution || step.execution.status !== 'DONE')\n .reduce(\n (groupedGasCosts, step) => {\n // We need to avoid destination chain step sufficiency check if we have LI.Fuel protocol sub-step\n const skipDueToRefuel =\n step.action.fromChainId === route?.toChainId && hasRefuelStep;\n if (\n step.estimate.gasCosts &&\n (account.connector as Connector)?.id !== 'safe' &&\n !skipDueToRefuel\n ) {\n const { token } = step.estimate.gasCosts[0];\n const gasCostAmount = step.estimate.gasCosts.reduce(\n (amount, gasCost) => amount + BigInt(gasCost.amount),\n 0n,\n );\n groupedGasCosts[token.chainId] = {\n gasAmount: groupedGasCosts[token.chainId]\n ? groupedGasCosts[token.chainId].gasAmount + gasCostAmount\n : gasCostAmount,\n token,\n };\n }\n // Add fees paid in native tokens to gas sufficiency check (included: false)\n const nonIncludedFeeCosts = step.estimate.feeCosts?.filter(\n (feeCost) => !feeCost.included,\n );\n if (nonIncludedFeeCosts?.length) {\n const { token } = nonIncludedFeeCosts[0];\n const feeCostAmount = nonIncludedFeeCosts.reduce(\n (amount, feeCost) => amount + BigInt(feeCost.amount),\n 0n,\n );\n groupedGasCosts[token.chainId] = {\n gasAmount: groupedGasCosts[token.chainId]\n ? groupedGasCosts[token.chainId].gasAmount + feeCostAmount\n : feeCostAmount,\n token,\n } as any;\n }\n return groupedGasCosts;\n },\n {} as Record,\n );\n\n // Check whether we are sending a native token\n // For native tokens we want to check for the total amount, including the network fee\n if (\n route!.fromToken.address === gasCosts[route!.fromChainId]?.token.address\n ) {\n gasCosts[route!.fromChainId].tokenAmount =\n gasCosts[route!.fromChainId]?.gasAmount + BigInt(route!.fromAmount);\n }\n\n const tokenBalances = await getTokenBalancesWithRetry(\n accountAddress!,\n Object.values(gasCosts).map((item) => item.token),\n );\n\n if (!tokenBalances?.length) {\n return [];\n }\n\n [route!.fromChainId, route!.toChainId].forEach((chainId) => {\n if (gasCosts[chainId]) {\n const gasTokenBalance =\n tokenBalances?.find(\n (t) =>\n t.chainId === gasCosts[chainId].token.chainId &&\n t.address === gasCosts[chainId].token.address,\n )?.amount ?? 0n;\n const insufficient =\n gasTokenBalance <= 0n ||\n gasTokenBalance < gasCosts[chainId].gasAmount ||\n gasTokenBalance < (gasCosts[chainId].tokenAmount ?? 0n);\n\n const insufficientAmount = insufficient\n ? gasCosts[chainId].tokenAmount\n ? gasCosts[chainId].tokenAmount! - gasTokenBalance\n : gasCosts[chainId].gasAmount - gasTokenBalance\n : undefined;\n\n gasCosts[chainId] = {\n ...gasCosts[chainId],\n insufficient,\n insufficientAmount,\n chain: insufficient ? getChainById(chainId) : undefined,\n };\n }\n });\n\n const gasCostResult = Object.values(gasCosts).filter(\n (gasCost) => gasCost.insufficient,\n );\n\n return gasCostResult;\n },\n\n enabled: Boolean(account.address && route),\n refetchInterval,\n staleTime: refetchInterval,\n });\n\n return {\n insufficientGas,\n isLoading,\n };\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M4.47 21h15.06c1.54 0 2.5-1.67 1.73-3L13.73 4.99c-.77-1.33-2.69-1.33-3.46 0L2.74 18c-.77 1.33.19 3 1.73 3M12 14c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1m1 4h-2v-2h2z\"\n}), 'WarningRounded');","import { WarningRounded } from '@mui/icons-material';\nimport { Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { AlertMessage } from '../AlertMessage/AlertMessage.js';\n\nexport const FundsSufficiencyMessage = () => {\n const { t } = useTranslation();\n return (\n }\n title={\n \n {t(`warning.message.insufficientFunds`)}\n \n }\n multilineTitle\n />\n );\n};\n","import { EvStation } from '@mui/icons-material';\nimport { Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { formatUnits } from 'viem';\nimport type { GasSufficiency } from '../../hooks/useGasSufficiency.js';\nimport { AlertMessage } from '../AlertMessage/AlertMessage.js';\n\ninterface GasSufficiencyMessageProps {\n insufficientGas?: GasSufficiency[];\n}\n\nexport const GasSufficiencyMessage: React.FC = ({\n insufficientGas,\n}) => {\n const { t } = useTranslation();\n return (\n }\n title={\n \n {t(`warning.title.insufficientGas`)}\n \n }\n >\n \n {t(`warning.message.insufficientGas`)}\n \n {insufficientGas?.map((item, index) => (\n \n {t(`main.tokenOnChainAmount`, {\n amount: formatUnits(\n item.insufficientAmount ?? 0n,\n item.token.decimals,\n ),\n tokenSymbol: item.token.symbol,\n chainName: item.chain?.name,\n })}\n \n ))}\n \n );\n};\n","import type { Route } from '@lifi/sdk';\nimport type { BoxProps } from '@mui/material';\nimport { Box, Collapse } from '@mui/material';\nimport { useFromTokenSufficiency } from '../../hooks/useFromTokenSufficiency.js';\nimport { useGasSufficiency } from '../../hooks/useGasSufficiency.js';\nimport { FundsSufficiencyMessage } from './FundsSufficiencyMessage.js';\nimport { GasSufficiencyMessage } from './GasSufficiencyMessage.js';\n\ninterface GasMessageProps extends BoxProps {\n route?: Route;\n}\n\nexport const GasMessage: React.FC = ({ route, ...props }) => {\n const { insufficientGas } = useGasSufficiency(route);\n const { insufficientFromToken } = useFromTokenSufficiency(route);\n\n const validInsufficientGas = insufficientGas?.length;\n\n return (\n \n \n {insufficientFromToken ? (\n \n ) : validInsufficientGas ? (\n \n ) : null}\n \n \n );\n};\n","import type { Route } from '@lifi/sdk';\nimport { Wallet } from '@mui/icons-material';\nimport type { BoxProps } from '@mui/material';\nimport { Box, Collapse, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useToAddressRequirements } from '../hooks/useToAddressRequirements.js';\nimport { useFieldValues } from '../stores/form/useFieldValues.js';\nimport { AlertMessage } from './AlertMessage/AlertMessage.js';\n\ninterface ToAddressRequiredMessageProps extends BoxProps {\n route?: Route;\n}\n\nexport const ToAddressRequiredMessage: React.FC<\n ToAddressRequiredMessageProps\n> = ({ route, ...props }) => {\n const { t } = useTranslation();\n const [toAddress] = useFieldValues('toAddress');\n const { requiredToAddress } = useToAddressRequirements();\n\n const showMessage = route && requiredToAddress && !toAddress;\n\n return (\n \n \n \n {t('info.message.toAddressIsRequired')}\n \n }\n icon={}\n multilineTitle\n />\n \n \n );\n};\n","import type { BoxProps } from '@mui/material';\nimport { GasMessage } from '../../components/GasMessage/GasMessage.js';\nimport { ToAddressRequiredMessage } from '../../components/ToAddressRequiredMessage.js';\nimport { useRoutes } from '../../hooks/useRoutes.js';\n\nexport const MainMessages: React.FC = (props) => {\n const { routes } = useRoutes();\n\n const currentRoute = routes?.[0];\n\n return (\n <>\n \n \n \n );\n};\n","import { LoadingButton } from '@mui/lab';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useChain } from '../../hooks/useChain.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport type { BaseTransactionButtonProps } from './types.js';\n\nexport const BaseTransactionButton: React.FC = ({\n onClick,\n text,\n disabled,\n loading,\n}) => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { walletConfig } = useWidgetConfig();\n const [fromChainId] = useFieldValues('fromChain');\n const { chain } = useChain(fromChainId);\n const { account } = useAccount({ chainType: chain?.chainType });\n\n const handleClick = async () => {\n if (account.isConnected) {\n onClick?.();\n } else if (walletConfig?.onConnect) {\n walletConfig.onConnect();\n } else {\n navigate(navigationRoutes.selectWallet);\n }\n };\n\n const getButtonText = () => {\n if (account.isConnected) {\n if (text) {\n return text;\n }\n }\n return t(`button.connectWallet`);\n };\n\n return (\n \n {getButtonText()}\n \n );\n};\n","import { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { BaseTransactionButton } from '../../components/BaseTransactionButton/BaseTransactionButton.js';\nimport { useRoutes } from '../../hooks/useRoutes.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { useSplitSubvariantStore } from '../../stores/settings/useSplitSubvariantStore.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\n\nexport const ReviewButton: React.FC = () => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { subvariant, subvariantOptions } = useWidgetConfig();\n const splitState = useSplitSubvariantStore((state) => state.state);\n const [toAddress] = useFieldValues('toAddress');\n const { requiredToAddress } = useToAddressRequirements();\n const { routes, setReviewableRoute } = useRoutes();\n\n const currentRoute = routes?.[0];\n\n const handleClick = async () => {\n if (currentRoute) {\n setReviewableRoute(currentRoute);\n navigate(navigationRoutes.transactionExecution, {\n state: { routeId: currentRoute.id },\n });\n }\n };\n\n const getButtonText = (): string => {\n if (currentRoute) {\n switch (subvariant) {\n case 'custom':\n return t(`button.${subvariantOptions?.custom ?? 'checkout'}Review`);\n case 'refuel':\n return t(`button.getGas`);\n default:\n const transactionType =\n currentRoute.fromChainId === currentRoute.toChainId\n ? 'swap'\n : 'bridge';\n return t(`button.${transactionType}Review`);\n }\n } else {\n switch (subvariant) {\n case 'custom':\n return subvariantOptions?.custom === 'deposit'\n ? t(`button.deposit`)\n : t(`button.buy`);\n case 'refuel':\n return t(`button.getGas`);\n case 'split':\n if (splitState) {\n return t(`button.${splitState}`);\n }\n return t(`button.exchange`);\n default:\n return t(`button.exchange`);\n }\n }\n };\n\n return (\n \n );\n};\n","import { useCallback } from 'react';\nimport { useNavigate } from 'react-router-dom';\n\nexport const useNavigateBack = () => {\n const navigate = useNavigate();\n\n const navigateBack = useCallback(() => {\n // TODO: find a better router with nested memory routers support\n // https://github.com/remix-run/react-router/pull/9112\n // https://github.com/remix-run/react-router/discussions/9601\n //\n // if (window.history.length > 2) {\n navigate(-1);\n // } else {\n // navigate(\n // window.location.pathname.substring(\n // 0,\n // window.location.pathname.lastIndexOf('/'),\n // ) || '/',\n // { replace: true },\n // );\n // }\n }, [navigate]);\n\n return { navigateBack, navigate };\n};\n","import { Stack as MuiStack, styled } from '@mui/material';\n\nexport const Stack = styled(MuiStack)(({ theme }) => ({\n position: 'relative',\n padding: theme.spacing(0, 3, 3, 3),\n}));\n","import debounce from '@mui/utils/debounce';\nexport default debounce;","import type { StateCreator } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport { createWithEqualityFn } from 'zustand/traditional';\nimport type { PersistStoreProps } from '../types.js';\nimport type { ChainOrderState } from './types.js';\n\nexport const maxChainsToOrder = 9;\nexport const maxChainsToShow = 10;\nconst defaultChainState = {\n from: [],\n to: [],\n};\n\nexport const createChainOrderStore = ({ namePrefix }: PersistStoreProps) =>\n createWithEqualityFn(\n persist(\n (set, get) => ({\n chainOrder: defaultChainState,\n availableChains: defaultChainState,\n initializeChains: (chainIds, type) => {\n set((state: ChainOrderState) => {\n const chainOrder = state.chainOrder[type].filter((chainId) =>\n chainIds.includes(chainId),\n );\n const chainsToAdd = chainIds.filter(\n (chainId) => !chainOrder.includes(chainId),\n );\n if (chainOrder.length === maxChainsToOrder || !chainsToAdd.length) {\n return {\n availableChains: {\n ...state.availableChains,\n [type]: chainIds,\n },\n chainOrder: {\n ...state.chainOrder,\n [type]: chainOrder,\n },\n };\n }\n const chainsToAddLength = maxChainsToOrder - chainOrder.length;\n for (let index = 0; index < chainsToAddLength; index++) {\n chainOrder.push(chainsToAdd[index]);\n }\n return {\n availableChains: {\n ...state.availableChains,\n [type]: chainIds,\n },\n chainOrder: {\n ...state.chainOrder,\n [type]: chainOrder,\n },\n };\n });\n return get().chainOrder[type];\n },\n setChain: (chainId, type) => {\n const state = get();\n if (\n state.chainOrder[type].includes(chainId) ||\n !state.availableChains[type].includes(chainId)\n ) {\n return;\n }\n set((state: ChainOrderState) => {\n const chainOrder = state.chainOrder[type].slice();\n chainOrder.unshift(chainId);\n if (chainOrder.length > maxChainsToOrder) {\n chainOrder.pop();\n }\n return {\n chainOrder: {\n ...state.chainOrder,\n [type]: chainOrder,\n },\n };\n });\n },\n }),\n {\n name: `${namePrefix || 'li.fi'}-widget-chains-order`,\n version: 2,\n partialize: (state) => ({ chainOrder: state.chainOrder }),\n },\n ) as StateCreator,\n Object.is,\n );\n","import { createContext, useContext, useEffect, useRef } from 'react';\nimport type { StoreApi } from 'zustand';\nimport type { UseBoundStoreWithEqualityFn } from 'zustand/traditional';\nimport { useChains } from '../../hooks/useChains.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { isItemAllowed } from '../../utils/item.js';\nimport type { FormType } from '../form/types.js';\nimport { useFieldActions } from '../form/useFieldActions.js';\nimport type { PersistStoreProviderProps } from '../types.js';\nimport { createChainOrderStore } from './createChainOrderStore.js';\nimport type { ChainOrderState } from './types.js';\n\nexport type ChainOrderStore = UseBoundStoreWithEqualityFn<\n StoreApi\n>;\n\nexport const ChainOrderStoreContext = createContext(\n null,\n);\n\nexport function ChainOrderStoreProvider({\n children,\n ...props\n}: PersistStoreProviderProps) {\n const { chains: configChains } = useWidgetConfig();\n const storeRef = useRef();\n const { chains } = useChains();\n const { setFieldValue, getFieldValues } = useFieldActions();\n\n if (!storeRef.current) {\n storeRef.current = createChainOrderStore(props);\n }\n\n useEffect(() => {\n if (chains) {\n (['from', 'to'] as FormType[]).forEach((key) => {\n const filteredChains = configChains?.[key]\n ? chains.filter((chain) => isItemAllowed(chain.id, configChains[key]))\n : chains;\n const chainOrder = storeRef.current?.getState().initializeChains(\n filteredChains.map((chain) => chain.id),\n key,\n );\n if (chainOrder) {\n const [chainValue] = getFieldValues(`${key}Chain`);\n if (!chainValue) {\n setFieldValue(`${key}Chain`, chainOrder[0]);\n }\n }\n });\n }\n }, [chains, configChains, getFieldValues, setFieldValue]);\n\n return (\n \n {children}\n \n );\n}\n\nexport function useChainOrderStoreContext() {\n const useStore = useContext(ChainOrderStoreContext);\n if (!useStore) {\n throw new Error(\n `You forgot to wrap your component in <${ChainOrderStoreProvider.name}>.`,\n );\n }\n return useStore;\n}\n\nexport function useChainOrderStore(\n selector: (state: ChainOrderState) => T,\n equalityFn?: (left: T, right: T) => boolean,\n): T {\n const useStore = useChainOrderStoreContext();\n return useStore(selector, equalityFn);\n}\n","import { shallow } from 'zustand/shallow';\nimport type { FormType } from '../form/types.js';\nimport { useChainOrderStore } from './ChainOrderStore.js';\n\nexport const useChainOrder = (\n type: FormType,\n): [number[], (chainId: number, type: FormType) => void] => {\n return useChainOrderStore(\n (state) => [state.chainOrder[type], state.setChain],\n shallow,\n );\n};\n","import type { EVMChain } from '@lifi/sdk';\nimport { useChains } from '../../hooks/useChains.js';\nimport { useSwapOnly } from '../../hooks/useSwapOnly.js';\nimport { useToAddressReset } from '../../hooks/useToAddressReset.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useChainOrder } from '../../stores/chains/useChainOrder.js';\nimport type { FormType } from '../../stores/form/types.js';\nimport { FormKeyHelper } from '../../stores/form/types.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useFieldController } from '../../stores/form/useFieldController.js';\nimport type { DisabledUI } from '../../types/widget.js';\n\nexport const useChainSelect = (formType: FormType) => {\n const { disabledUI } = useWidgetConfig();\n const chainKey = FormKeyHelper.getChainKey(formType);\n const { onChange } = useFieldController({ name: chainKey });\n const { setFieldValue, getFieldValues } = useFieldActions();\n const { chains, isLoading, getChainById } = useChains(formType);\n const [chainOrder, setChainOrder] = useChainOrder(formType);\n const swapOnly = useSwapOnly();\n const { tryResetToAddress } = useToAddressReset();\n\n const getChains = () => {\n if (!chains) {\n return [];\n }\n const selectedChains = chainOrder\n .map((chainId) => chains.find((chain) => chain.id === chainId))\n .filter(Boolean) as EVMChain[];\n return selectedChains;\n };\n\n const setCurrentChain = (chainId: number) => {\n onChange(chainId);\n if (swapOnly) {\n setFieldValue(FormKeyHelper.getChainKey('to'), chainId, {\n isTouched: true,\n });\n }\n const tokenKey = FormKeyHelper.getTokenKey(formType);\n if (!disabledUI?.includes(tokenKey as DisabledUI)) {\n setFieldValue(tokenKey, '');\n }\n const amountKey = FormKeyHelper.getAmountKey(formType);\n if (!disabledUI?.includes(amountKey as DisabledUI)) {\n setFieldValue(amountKey, '');\n }\n setFieldValue('tokenSearchFilter', '');\n\n const [toChainId] = getFieldValues('toChain');\n const toChain = getChainById(toChainId);\n if (toChain) {\n tryResetToAddress(toChain);\n }\n setChainOrder(chainId, formType);\n };\n\n return {\n chainOrder,\n chains,\n getChains,\n isLoading,\n setChainOrder,\n setCurrentChain,\n };\n};\n","import { styled } from '@mui/material';\nimport type { PageContainerProps } from './PageContainer.js';\nimport { PageContainer } from './PageContainer.js';\n\n// In max height and default layout\n// the PageContainer collapses to use the minimum space need to display its child components whereas\n// the FullPageContainer expands and fills the available vertical space provide by the max-height\n// See the CssBaselineContainer component styles in AppContainer.tsx for usage of full-page-container\nexport const FullPageContainer = styled((props: PageContainerProps) => (\n \n))``;\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14\"\n}), 'Search');","import { InputBase, inputBaseClasses, styled } from '@mui/material';\n\nexport const Input = styled(InputBase)(({ theme }) => ({\n paddingRight: theme.spacing(2),\n [`.${inputBaseClasses.input}`]: {\n padding: theme.spacing(1.5, 1, 1.5, 2),\n height: '2.875em',\n boxSizing: 'inherit',\n },\n fontWeight: 500,\n}));\n","import { Box, List, styled } from '@mui/material';\nimport { Input as InputBase } from '../../components/Input.js';\n\nexport const Input = styled(InputBase)(({ theme }) => ({\n paddingRight: theme.spacing(1.5),\n}));\n\ninterface SearchStickyContainerProps {\n headerHeight: number;\n}\n\nexport const searchContainerHeight = 64;\n\n// When the widget is in Full Height layout mode in order to appear \"sticky the StickySearchInputContainer needs to use\n// position fixed in the same way as the header (see Header.tsx). The headerHeight value here is used as the top value\n// to ensure that this container positioned correctly beneath the header\nexport const StickySearchInputContainer = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'headerHeight',\n})(({ theme, headerHeight }) => ({\n position: 'sticky',\n top: headerHeight,\n zIndex: 1,\n height: searchContainerHeight,\n paddingBottom: theme.spacing(2),\n paddingLeft: theme.spacing(3),\n paddingRight: theme.spacing(3),\n backgroundColor: theme.palette.background.default,\n ...(theme.header?.position === 'fixed'\n ? {\n position: 'fixed',\n minWidth: theme.breakpoints.values.xs,\n maxWidth: theme.breakpoints.values.sm,\n width: '100%',\n }\n : {}),\n}));\n\n// When in Full Height layout mode, as the StickySearchInputContainer (see above) uses fixed position, the list element needs to provide\n// additional paddingTop in order to be positioned correctly.\nexport const SearchList = styled(List)(({ theme }) => ({\n paddingTop:\n theme.header?.position === 'fixed' ? `${searchContainerHeight}px` : 0,\n paddingLeft: theme.spacing(1.5),\n paddingRight: theme.spacing(1.5),\n paddingBottom: theme.spacing(1.5),\n}));\n","import { Search } from '@mui/icons-material';\nimport { FormControl, InputAdornment } from '@mui/material';\nimport type { FocusEventHandler, FormEventHandler } from 'react';\nimport { InputCard } from '../../components/Card/InputCard.js';\nimport { useHeaderHeight } from '../../stores/header/useHeaderStore.js';\nimport { Input, StickySearchInputContainer } from './SearchInput.style.js';\n\ninterface SearchInputProps {\n name?: string;\n value?: string;\n placeholder?: string;\n onChange?: FormEventHandler;\n onBlur?: FocusEventHandler;\n}\n\nexport const SearchInput = ({\n name,\n placeholder,\n onChange,\n onBlur,\n value,\n}: SearchInputProps) => {\n return (\n \n \n \n \n \n }\n inputProps={{\n inputMode: 'search',\n onChange,\n onBlur,\n name,\n value,\n maxLength: 128,\n }}\n autoComplete=\"off\"\n />\n \n \n );\n};\n\nexport const StickySearchInput = ({ ...rest }: SearchInputProps) => {\n const { headerHeight } = useHeaderHeight();\n\n return (\n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon([/*#__PURE__*/_jsx(\"path\", {\n d: \"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3 6.08 3 3.28 5.64 3.03 9h2.02C5.3 6.75 7.18 5 9.5 5 11.99 5 14 7.01 14 9.5S11.99 14 9.5 14c-.17 0-.33-.03-.5-.05v2.02c.17.02.33.03.5.03 1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19z\"\n}, \"0\"), /*#__PURE__*/_jsx(\"path\", {\n d: \"M6.47 10.82 4 13.29l-2.47-2.47-.71.71L3.29 14 .82 16.47l.71.71L4 14.71l2.47 2.47.71-.71L4.71 14l2.47-2.47z\"\n}, \"1\")], 'SearchOff');","import type { BoxProps } from '@mui/material';\nimport { Box, styled, Typography } from '@mui/material';\nimport { searchContainerHeight } from './SearchInput.style.js';\n\ninterface NotFoundContainerProps extends BoxProps {\n adjustForStickySearchInput?: boolean;\n}\n\nexport const NotFoundContainer = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'adjustForStickySearchInput',\n})(({ theme, adjustForStickySearchInput }) => ({\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n flexDirection: 'column',\n flex: 1,\n padding: theme.spacing(3),\n ...(adjustForStickySearchInput && theme.header?.position === 'fixed'\n ? { paddingTop: `calc(${searchContainerHeight}px + ${theme.spacing(3)})` }\n : {}),\n}));\n\nexport const NotFoundMessage = styled(Typography)(({ theme }) => ({\n fontSize: 14,\n color: theme.palette.text.secondary,\n textAlign: 'center',\n flex: 1,\n marginTop: theme.spacing(2),\n paddingLeft: theme.spacing(2),\n paddingRight: theme.spacing(2),\n}));\n\nexport const NotFoundIconContainer = styled(Typography)(({ theme }) => ({\n fontSize: 48,\n lineHeight: 1,\n}));\n","import { SearchOff } from '@mui/icons-material';\nimport {\n NotFoundContainer,\n NotFoundIconContainer,\n NotFoundMessage,\n} from './SearchNotFound.style.js';\n\ninterface SearchNotFoundProps {\n message: string;\n adjustForStickySearchInput?: boolean;\n}\n\nexport const SearchNotFound = ({\n message,\n adjustForStickySearchInput,\n}: SearchNotFoundProps) => (\n \n \n \n \n {message}\n \n);\n","import { useCallback } from 'react';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useChainOrderStoreContext } from '../../stores/chains/ChainOrderStore.js';\nimport type { FormType } from '../../stores/form/types.js';\nimport { FormKeyHelper } from '../../stores/form/types.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useFieldController } from '../../stores/form/useFieldController.js';\nimport { WidgetEvent } from '../../types/events.js';\nimport type { DisabledUI } from '../../types/widget.js';\n\nexport const useTokenSelect = (formType: FormType, onClick?: () => void) => {\n const { subvariant, disabledUI } = useWidgetConfig();\n const emitter = useWidgetEvents();\n const { setFieldValue, getFieldValues } = useFieldActions();\n const tokenKey = FormKeyHelper.getTokenKey(formType);\n const { onChange } = useFieldController({ name: tokenKey });\n const chainOrderStore = useChainOrderStoreContext();\n\n return useCallback(\n (tokenAddress: string, chainId?: number) => {\n onChange(tokenAddress);\n const selectedChainId =\n chainId ?? getFieldValues(FormKeyHelper.getChainKey(formType))[0];\n // Set chain again to trigger URL builder update\n setFieldValue(FormKeyHelper.getChainKey(formType), selectedChainId, {\n isDirty: true,\n isTouched: true,\n });\n const amountKey = FormKeyHelper.getAmountKey(formType);\n if (!disabledUI?.includes(amountKey as DisabledUI)) {\n setFieldValue(amountKey, '');\n }\n const oppositeFormType = formType === 'from' ? 'to' : 'from';\n const [selectedOppositeToken, selectedOppositeChainId] = getFieldValues(\n FormKeyHelper.getTokenKey(oppositeFormType),\n FormKeyHelper.getChainKey(oppositeFormType),\n );\n // TODO: remove when we enable same chain/token transfers\n if (\n selectedOppositeToken === tokenAddress &&\n selectedOppositeChainId === selectedChainId &&\n subvariant !== 'custom'\n ) {\n setFieldValue(FormKeyHelper.getTokenKey(oppositeFormType), '', {\n isDirty: true,\n isTouched: true,\n });\n }\n\n // Check if the selected source chain matches any chain on the destination chain selection view (chainOrder array).\n // If a match exists and the destination token is not selected, update the destination chain to match the source.\n if (\n formType === 'from' &&\n !selectedOppositeToken &&\n selectedChainId &&\n chainOrderStore.getState().chainOrder.to.includes(selectedChainId)\n ) {\n setFieldValue(FormKeyHelper.getChainKey('to'), selectedChainId, {\n isDirty: true,\n isTouched: true,\n });\n }\n\n const eventToEmit =\n formType === 'from'\n ? WidgetEvent.SourceChainTokenSelected\n : WidgetEvent.DestinationChainTokenSelected;\n\n if (selectedChainId) {\n emitter.emit(eventToEmit, {\n chainId: selectedChainId,\n tokenAddress,\n });\n }\n\n onClick?.();\n },\n [\n chainOrderStore,\n disabledUI,\n emitter,\n formType,\n getFieldValues,\n onChange,\n onClick,\n setFieldValue,\n subvariant,\n ],\n );\n};\n","import type { ExtendedChain } from '@lifi/sdk';\nimport { Avatar, debounce, ListItemAvatar } from '@mui/material';\nimport { type FormEventHandler, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useChainSelect } from '../../components/ChainSelect/useChainSelect.js';\nimport { FullPageContainer } from '../../components/FullPageContainer.js';\nimport { ListItemButton } from '../../components/ListItemButton.js';\nimport { ListItemText } from '../../components/ListItemText.js';\nimport { StickySearchInput } from '../../components/Search/SearchInput.js';\nimport { SearchList } from '../../components/Search/SearchInput.style.js';\nimport { SearchNotFound } from '../../components/Search/SearchNotFound.js';\nimport { useTokenSelect } from '../../components/TokenList/useTokenSelect.js';\nimport { useDefaultElementId } from '../../hooks/useDefaultElementId.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useScrollableContainer } from '../../hooks/useScrollableContainer.js';\nimport type { SelectChainPageProps } from './types.js';\n\nexport const SelectChainPage: React.FC = ({\n formType,\n selectNativeToken,\n}) => {\n const { navigateBack } = useNavigateBack();\n const { chains, setCurrentChain } = useChainSelect(formType);\n const selectToken = useTokenSelect(formType, navigateBack);\n const elementId = useDefaultElementId();\n const scrollableContainer = useScrollableContainer(elementId);\n\n const { t } = useTranslation();\n\n useHeader(t('header.selectChain'));\n\n const handleClick = async (chain: ExtendedChain) => {\n if (selectNativeToken) {\n selectToken(chain.nativeToken.address, chain.id);\n } else {\n setCurrentChain(chain.id);\n navigateBack();\n }\n };\n\n const [filteredChains, setFilteredChains] = useState(\n chains ?? [],\n );\n\n const handleSearchInputChange: FormEventHandler = (e) => {\n const value = (e.target as HTMLInputElement).value;\n\n if (!value) {\n setFilteredChains(chains ?? []);\n } else {\n setFilteredChains(\n chains\n ? chains.filter((chain) =>\n chain.name.toLowerCase().includes(value.toLowerCase()),\n )\n : [],\n );\n }\n\n if (scrollableContainer) {\n scrollableContainer.scrollTop = 0;\n }\n };\n\n const debouncedSearchInputChange = debounce(handleSearchInputChange, 250);\n\n return (\n \n \n {filteredChains.length ? (\n \n {filteredChains.map((chain) => (\n handleClick(chain)}>\n \n \n {chain.name[0]}\n \n \n \n \n ))}\n \n ) : (\n \n )}\n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14zM17.99 9l-1.41-1.42-6.59 6.59-2.58-2.57-1.42 1.41 4 3.99z\"\n}), 'CheckBoxOutlined');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14zM7 11h10v2H7z\"\n}), 'IndeterminateCheckBoxOutlined');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19 5v14H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2\"\n}), 'CheckBoxOutlineBlankOutlined');","import { getTools, type ToolsResponse } from '@lifi/sdk';\nimport { useQuery } from '@tanstack/react-query';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { useSettingsStore } from '../stores/settings/useSettingsStore.js';\nimport { isItemAllowed } from '../utils/item.js';\n\nexport const useTools = () => {\n const { bridges, exchanges } = useWidgetConfig();\n const { data } = useQuery({\n queryKey: [\n 'tools',\n bridges?.allow,\n bridges?.deny,\n exchanges?.allow,\n exchanges?.deny,\n ],\n queryFn: async (): Promise => {\n const tools = await getTools();\n const result = {\n bridges: tools.bridges.filter((bridge) =>\n isItemAllowed(bridge.key, bridges),\n ),\n exchanges: tools.exchanges.filter((exchange) =>\n isItemAllowed(exchange.key, exchanges),\n ),\n };\n const { initializeTools } = useSettingsStore.getState();\n initializeTools(\n 'Bridges',\n result.bridges.map((bridge) => bridge.key),\n );\n initializeTools(\n 'Exchanges',\n result.exchanges.map((exchange) => exchange.key),\n );\n return result;\n },\n refetchInterval: 180_000,\n staleTime: 180_000,\n });\n\n return { tools: data };\n};\n","import type { ToolsResponse } from '@lifi/sdk';\nimport {\n Check,\n CheckBoxOutlineBlankOutlined,\n CheckBoxOutlined,\n IndeterminateCheckBoxOutlined,\n} from '@mui/icons-material';\nimport {\n Avatar,\n debounce,\n IconButton,\n ListItemAvatar,\n Tooltip,\n useTheme,\n} from '@mui/material';\nimport type { MouseEventHandler } from 'react';\nimport { type FormEventHandler, useMemo, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { shallow } from 'zustand/shallow';\nimport { FullPageContainer } from '../components/FullPageContainer.js';\nimport { ListItemText } from '../components/ListItemText.js';\nimport { StickySearchInput } from '../components/Search/SearchInput.js';\nimport { SearchList } from '../components/Search/SearchInput.style.js';\nimport { SearchNotFound } from '../components/Search/SearchNotFound.js';\nimport { SettingsListItemButton } from '../components/SettingsListItemButton.js';\nimport { useDefaultElementId } from '../hooks/useDefaultElementId.js';\nimport { useHeader } from '../hooks/useHeader.js';\nimport { useScrollableContainer } from '../hooks/useScrollableContainer.js';\nimport { useTools } from '../hooks/useTools.js';\nimport { useSettingsStore } from '../stores/settings/useSettingsStore.js';\n\ninterface SelectAllCheckboxProps {\n allCheckboxesSelected: boolean;\n onClick: MouseEventHandler;\n anyCheckboxesSelected: boolean;\n noCheckboxesAvailable: boolean;\n}\n\nconst SelectAllCheckbox: React.FC = ({\n allCheckboxesSelected,\n anyCheckboxesSelected,\n noCheckboxesAvailable,\n onClick,\n}) => {\n const { t } = useTranslation();\n const theme = useTheme();\n const tooltipTitle = noCheckboxesAvailable\n ? undefined\n : allCheckboxesSelected\n ? t('tooltip.deselectAll')\n : t('tooltip.selectAll');\n\n return (\n \n \n {allCheckboxesSelected ? (\n \n ) : anyCheckboxesSelected ? (\n \n ) : (\n \n )}\n \n \n );\n};\n\ntype ToolCollectionTypes =\n | ToolsResponse['exchanges']\n | ToolsResponse['bridges'];\n\nexport const SelectEnabledToolsPage: React.FC<{\n type: 'Bridges' | 'Exchanges';\n}> = ({ type }) => {\n const typeKey = type.toLowerCase() as 'bridges' | 'exchanges';\n const { tools } = useTools();\n const [enabledTools, disabledTools, setToolValue, toggleToolKeys] =\n useSettingsStore(\n (state) => [\n state[`_enabled${type}`],\n state[`disabled${type}`],\n state.setToolValue,\n state.toggleToolKeys,\n ],\n shallow,\n );\n\n const { t } = useTranslation();\n const elementId = useDefaultElementId();\n const scrollableContainer = useScrollableContainer(elementId);\n const [filteredTools, setFilteredTools] = useState(\n tools?.[typeKey] ?? [],\n );\n\n const headerAction = useMemo(\n () => (\n !disabledTools.includes(tool.key))\n }\n anyCheckboxesSelected={\n !!filteredTools.length &&\n filteredTools.some((tool) => disabledTools.includes(tool.key))\n }\n noCheckboxesAvailable={!filteredTools.length}\n onClick={() =>\n toggleToolKeys(\n type,\n filteredTools.map((tool) => tool.key),\n )\n }\n />\n ),\n [disabledTools, toggleToolKeys, type, filteredTools],\n );\n\n useHeader(t(`settings.enabled${type}`), headerAction);\n\n const handleClick = (key: string) => {\n setToolValue(type, key, !enabledTools[key]);\n };\n\n const handleSearchInputChange: FormEventHandler = (e) => {\n const value = (e.target as HTMLInputElement).value;\n\n if (!value) {\n setFilteredTools(tools?.[typeKey] ?? []);\n } else {\n setFilteredTools(\n (tools?.[typeKey]\n ? tools[typeKey].filter((tool) =>\n tool.name.toLowerCase().includes(value.toLowerCase()),\n )\n : []) as ToolCollectionTypes,\n );\n }\n\n if (scrollableContainer) {\n scrollableContainer.scrollTop = 0;\n }\n };\n\n const debouncedSearchInputChange = debounce(handleSearchInputChange, 250);\n\n return (\n \n \n {filteredTools.length ? (\n \n {filteredTools.map((tool) => (\n handleClick(tool.key)}\n >\n \n \n {tool.name[0]}\n \n \n \n {enabledTools[tool.key] && }\n \n ))}\n \n ) : (\n \n )}\n \n );\n};\n","import { Box, styled } from '@mui/material';\nimport { Card } from '../../components/Card/Card.js';\n\nexport const ChainCard = styled(Card)({\n display: 'grid',\n placeItems: 'center',\n minWidth: 52,\n height: 56,\n});\n\nexport const ChainContainer = styled(Box)(({ theme }) => ({\n display: 'grid',\n gridTemplateColumns: 'repeat(auto-fit, minmax(52px, 1fr))',\n gridAutoRows: '56px',\n justifyContent: 'space-between',\n gap: theme.spacing(1.5),\n}));\n","/* eslint-disable react/no-array-index-key */\nimport type { EVMChain } from '@lifi/sdk';\nimport { Avatar, Box, Skeleton, Tooltip, Typography } from '@mui/material';\nimport { useEffect } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport {\n maxChainsToOrder,\n maxChainsToShow,\n} from '../../stores/chains/createChainOrderStore.js';\nimport type { FormTypeProps } from '../../stores/form/types.js';\nimport { FormKeyHelper } from '../../stores/form/types.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { ChainCard, ChainContainer } from './ChainSelect.style.js';\nimport { useChainSelect } from './useChainSelect.js';\n\nexport const ChainSelect = ({ formType }: FormTypeProps) => {\n const navigate = useNavigate();\n const {\n chainOrder,\n chains,\n getChains,\n isLoading,\n setChainOrder,\n setCurrentChain,\n } = useChainSelect(formType);\n\n const [chainId] = useFieldValues(FormKeyHelper.getChainKey(formType));\n\n useEffect(() => {\n if (chainId) {\n const hasChainInOrderedList = chainOrder.includes(chainId);\n // If we don't have a chain in the ordered chain list we should add it.\n if (!hasChainInOrderedList) {\n setChainOrder(chainId, formType);\n }\n }\n }, [chainId, chainOrder, formType, setChainOrder]);\n\n const showAllChains = () => {\n navigate(navigationRoutes[`${formType}Chain`]);\n };\n\n // We check if we can accommodate all the chains on the grid\n // If there are more than 10 chains we show the number of hidden chains as the last one tile\n const chainsToHide =\n chains?.length === maxChainsToShow\n ? 0\n : (chains?.length ?? 0) - maxChainsToOrder;\n\n // When there is less than 10 chains we don't care about the order\n const chainsToShow = chainsToHide > 0 ? getChains() : chains;\n\n return (\n \n {isLoading\n ? Array.from({ length: maxChainsToOrder }).map((_, index) => (\n \n ))\n : chainsToShow?.map((chain: EVMChain) => (\n \n setCurrentChain(chain.id)}\n type={chainId === chain.id ? 'selected' : 'default'}\n selectionColor=\"primary\"\n >\n \n {chain.name[0]}\n \n \n \n ))}\n {chainsToHide > 0 ? (\n \n \n +{chainsToHide}\n \n \n ) : null}\n \n );\n};\n","import { useTranslation } from 'react-i18next';\nimport { useAvailableChains } from '../../hooks/useAvailableChains.js';\nimport type { FormTypeProps } from '../../stores/form/types.js';\nimport { FormKeyHelper } from '../../stores/form/types.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { SearchNotFound } from '../Search/SearchNotFound.js';\n\nexport const TokenNotFound: React.FC = ({ formType }) => {\n const { t } = useTranslation();\n const [selectedChainId] = useFieldValues(FormKeyHelper.getChainKey(formType));\n const { getChainById } = useAvailableChains();\n\n return (\n \n );\n};\n","export type NoInfer
= [A][A extends any ? 0 : never]\n\nexport type PartialKeys = Omit & Partial>\n\nexport function memo, TResult>(\n getDeps: () => [...TDeps],\n fn: (...args: NoInfer<[...TDeps]>) => TResult,\n opts: {\n key: false | string\n debug?: () => boolean\n onChange?: (result: TResult) => void\n initialDeps?: TDeps\n },\n) {\n let deps = opts.initialDeps ?? []\n let result: TResult | undefined\n\n return (): TResult => {\n let depTime: number\n if (opts.key && opts.debug?.()) depTime = Date.now()\n\n const newDeps = getDeps()\n\n const depsChanged =\n newDeps.length !== deps.length ||\n newDeps.some((dep: any, index: number) => deps[index] !== dep)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n let resultTime: number\n if (opts.key && opts.debug?.()) resultTime = Date.now()\n\n result = fn(...newDeps)\n\n if (opts.key && opts.debug?.()) {\n const depEndTime = Math.round((Date.now() - depTime!) * 100) / 100\n const resultEndTime = Math.round((Date.now() - resultTime!) * 100) / 100\n const resultFpsPercentage = resultEndTime / 16\n\n const pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n }\n\n console.info(\n `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n `\n font-size: .6rem;\n font-weight: bold;\n color: hsl(${Math.max(\n 0,\n Math.min(120 - 120 * resultFpsPercentage, 120),\n )}deg 100% 31%);`,\n opts?.key,\n )\n }\n\n opts?.onChange?.(result)\n\n return result\n }\n}\n\nexport function notUndefined(value: T | undefined, msg?: string): T {\n if (value === undefined) {\n throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`)\n } else {\n return value\n }\n}\n\nexport const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1\n\nexport const debounce = (\n targetWindow: Window & typeof globalThis,\n fn: Function,\n ms: number,\n) => {\n let timeoutId: number\n return function (this: any, ...args: Array) {\n targetWindow.clearTimeout(timeoutId)\n timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms)\n }\n}\n","import { approxEqual, debounce, memo, notUndefined } from './utils'\n\nexport * from './utils'\n\n//\n\ntype ScrollDirection = 'forward' | 'backward'\n\ntype ScrollAlignment = 'start' | 'center' | 'end' | 'auto'\n\ntype ScrollBehavior = 'auto' | 'smooth'\n\nexport interface ScrollToOptions {\n align?: ScrollAlignment\n behavior?: ScrollBehavior\n}\n\ntype ScrollToOffsetOptions = ScrollToOptions\n\ntype ScrollToIndexOptions = ScrollToOptions\n\nexport interface Range {\n startIndex: number\n endIndex: number\n overscan: number\n count: number\n}\n\ntype Key = number | string | bigint\n\nexport interface VirtualItem {\n key: Key\n index: number\n start: number\n end: number\n size: number\n lane: number\n}\n\nexport interface Rect {\n width: number\n height: number\n}\n\n//\n\nexport const defaultKeyExtractor = (index: number) => index\n\nexport const defaultRangeExtractor = (range: Range) => {\n const start = Math.max(range.startIndex - range.overscan, 0)\n const end = Math.min(range.endIndex + range.overscan, range.count - 1)\n\n const arr = []\n\n for (let i = start; i <= end; i++) {\n arr.push(i)\n }\n\n return arr\n}\n\nexport const observeElementRect = (\n instance: Virtualizer,\n cb: (rect: Rect) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n const targetWindow = instance.targetWindow\n if (!targetWindow) {\n return\n }\n\n const handler = (rect: Rect) => {\n const { width, height } = rect\n cb({ width: Math.round(width), height: Math.round(height) })\n }\n\n handler(element.getBoundingClientRect())\n\n if (!targetWindow.ResizeObserver) {\n return () => {}\n }\n\n const observer = new targetWindow.ResizeObserver((entries) => {\n const entry = entries[0]\n if (entry?.borderBoxSize) {\n const box = entry.borderBoxSize[0]\n if (box) {\n handler({ width: box.inlineSize, height: box.blockSize })\n return\n }\n }\n handler(element.getBoundingClientRect())\n })\n\n observer.observe(element, { box: 'border-box' })\n\n return () => {\n observer.unobserve(element)\n }\n}\n\nconst addEventListenerOptions = {\n passive: true,\n}\n\nexport const observeWindowRect = (\n instance: Virtualizer,\n cb: (rect: Rect) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n\n const handler = () => {\n cb({ width: element.innerWidth, height: element.innerHeight })\n }\n handler()\n\n element.addEventListener('resize', handler, addEventListenerOptions)\n\n return () => {\n element.removeEventListener('resize', handler)\n }\n}\n\nconst supportsScrollend =\n typeof window == 'undefined' ? true : 'onscrollend' in window\n\nexport const observeElementOffset = (\n instance: Virtualizer,\n cb: (offset: number, isScrolling: boolean) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n const targetWindow = instance.targetWindow\n if (!targetWindow) {\n return\n }\n\n let offset = 0\n const fallback = supportsScrollend\n ? () => undefined\n : debounce(\n targetWindow,\n () => {\n cb(offset, false)\n },\n instance.options.isScrollingResetDelay,\n )\n\n const createHandler = (isScrolling: boolean) => () => {\n const { horizontal, isRtl } = instance.options\n offset = horizontal\n ? element['scrollLeft'] * ((isRtl && -1) || 1)\n : element['scrollTop']\n fallback()\n cb(offset, isScrolling)\n }\n const handler = createHandler(true)\n const endHandler = createHandler(false)\n endHandler()\n\n element.addEventListener('scroll', handler, addEventListenerOptions)\n element.addEventListener('scrollend', endHandler, addEventListenerOptions)\n\n return () => {\n element.removeEventListener('scroll', handler)\n element.removeEventListener('scrollend', endHandler)\n }\n}\n\nexport const observeWindowOffset = (\n instance: Virtualizer,\n cb: (offset: number, isScrolling: boolean) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n const targetWindow = instance.targetWindow\n if (!targetWindow) {\n return\n }\n\n let offset = 0\n const fallback = supportsScrollend\n ? () => undefined\n : debounce(\n targetWindow,\n () => {\n cb(offset, false)\n },\n instance.options.isScrollingResetDelay,\n )\n\n const createHandler = (isScrolling: boolean) => () => {\n offset = element[instance.options.horizontal ? 'scrollX' : 'scrollY']\n fallback()\n cb(offset, isScrolling)\n }\n const handler = createHandler(true)\n const endHandler = createHandler(false)\n endHandler()\n\n element.addEventListener('scroll', handler, addEventListenerOptions)\n element.addEventListener('scrollend', endHandler, addEventListenerOptions)\n\n return () => {\n element.removeEventListener('scroll', handler)\n element.removeEventListener('scrollend', endHandler)\n }\n}\n\nexport const measureElement = (\n element: TItemElement,\n entry: ResizeObserverEntry | undefined,\n instance: Virtualizer,\n) => {\n if (entry?.borderBoxSize) {\n const box = entry.borderBoxSize[0]\n if (box) {\n const size = Math.round(\n box[instance.options.horizontal ? 'inlineSize' : 'blockSize'],\n )\n return size\n }\n }\n return Math.round(\n element.getBoundingClientRect()[\n instance.options.horizontal ? 'width' : 'height'\n ],\n )\n}\n\nexport const windowScroll = (\n offset: number,\n {\n adjustments = 0,\n behavior,\n }: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer,\n) => {\n const toOffset = offset + adjustments\n\n instance.scrollElement?.scrollTo?.({\n [instance.options.horizontal ? 'left' : 'top']: toOffset,\n behavior,\n })\n}\n\nexport const elementScroll = (\n offset: number,\n {\n adjustments = 0,\n behavior,\n }: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer,\n) => {\n const toOffset = offset + adjustments\n\n instance.scrollElement?.scrollTo?.({\n [instance.options.horizontal ? 'left' : 'top']: toOffset,\n behavior,\n })\n}\n\nexport interface VirtualizerOptions<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> {\n // Required from the user\n count: number\n getScrollElement: () => TScrollElement | null\n estimateSize: (index: number) => number\n\n // Required from the framework adapter (but can be overridden)\n scrollToFn: (\n offset: number,\n options: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer,\n ) => void\n observeElementRect: (\n instance: Virtualizer,\n cb: (rect: Rect) => void,\n ) => void | (() => void)\n observeElementOffset: (\n instance: Virtualizer,\n cb: (offset: number, isScrolling: boolean) => void,\n ) => void | (() => void)\n\n // Optional\n debug?: boolean\n initialRect?: Rect\n onChange?: (\n instance: Virtualizer,\n sync: boolean,\n ) => void\n measureElement?: (\n element: TItemElement,\n entry: ResizeObserverEntry | undefined,\n instance: Virtualizer,\n ) => number\n overscan?: number\n horizontal?: boolean\n paddingStart?: number\n paddingEnd?: number\n scrollPaddingStart?: number\n scrollPaddingEnd?: number\n initialOffset?: number | (() => number)\n getItemKey?: (index: number) => Key\n rangeExtractor?: (range: Range) => Array\n scrollMargin?: number\n gap?: number\n indexAttribute?: string\n initialMeasurementsCache?: Array\n lanes?: number\n isScrollingResetDelay?: number\n enabled?: boolean\n isRtl?: boolean\n}\n\nexport class Virtualizer<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> {\n private unsubs: Array void)> = []\n options!: Required>\n scrollElement: TScrollElement | null = null\n targetWindow: (Window & typeof globalThis) | null = null\n isScrolling = false\n private scrollToIndexTimeoutId: number | null = null\n measurementsCache: Array = []\n private itemSizeCache = new Map()\n private pendingMeasuredCacheIndexes: Array = []\n scrollRect: Rect | null = null\n scrollOffset: number | null = null\n scrollDirection: ScrollDirection | null = null\n private scrollAdjustments = 0\n shouldAdjustScrollPositionOnItemSizeChange:\n | undefined\n | ((\n item: VirtualItem,\n delta: number,\n instance: Virtualizer,\n ) => boolean)\n elementsCache = new Map()\n private observer = (() => {\n let _ro: ResizeObserver | null = null\n\n const get = () => {\n if (_ro) {\n return _ro\n }\n\n if (!this.targetWindow || !this.targetWindow.ResizeObserver) {\n return null\n }\n\n return (_ro = new this.targetWindow.ResizeObserver((entries) => {\n entries.forEach((entry) => {\n this._measureElement(entry.target as TItemElement, entry)\n })\n }))\n }\n\n return {\n disconnect: () => {\n get()?.disconnect()\n _ro = null\n },\n observe: (target: Element) =>\n get()?.observe(target, { box: 'border-box' }),\n unobserve: (target: Element) => get()?.unobserve(target),\n }\n })()\n range: { startIndex: number; endIndex: number } | null = null\n\n constructor(opts: VirtualizerOptions) {\n this.setOptions(opts)\n }\n\n setOptions = (opts: VirtualizerOptions) => {\n Object.entries(opts).forEach(([key, value]) => {\n if (typeof value === 'undefined') delete (opts as any)[key]\n })\n\n this.options = {\n debug: false,\n initialOffset: 0,\n overscan: 1,\n paddingStart: 0,\n paddingEnd: 0,\n scrollPaddingStart: 0,\n scrollPaddingEnd: 0,\n horizontal: false,\n getItemKey: defaultKeyExtractor,\n rangeExtractor: defaultRangeExtractor,\n onChange: () => {},\n measureElement,\n initialRect: { width: 0, height: 0 },\n scrollMargin: 0,\n gap: 0,\n indexAttribute: 'data-index',\n initialMeasurementsCache: [],\n lanes: 1,\n isScrollingResetDelay: 150,\n enabled: true,\n isRtl: false,\n ...opts,\n }\n }\n\n private notify = (sync: boolean) => {\n this.options.onChange?.(this, sync)\n }\n\n private maybeNotify = memo(\n () => {\n this.calculateRange()\n\n return [\n this.isScrolling,\n this.range ? this.range.startIndex : null,\n this.range ? this.range.endIndex : null,\n ]\n },\n (isScrolling) => {\n this.notify(isScrolling)\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'maybeNotify',\n debug: () => this.options.debug,\n initialDeps: [\n this.isScrolling,\n this.range ? this.range.startIndex : null,\n this.range ? this.range.endIndex : null,\n ] as [boolean, number | null, number | null],\n },\n )\n\n private cleanup = () => {\n this.unsubs.filter(Boolean).forEach((d) => d!())\n this.unsubs = []\n this.observer.disconnect()\n this.scrollElement = null\n this.targetWindow = null\n }\n\n _didMount = () => {\n return () => {\n this.cleanup()\n }\n }\n\n _willUpdate = () => {\n const scrollElement = this.options.enabled\n ? this.options.getScrollElement()\n : null\n\n if (this.scrollElement !== scrollElement) {\n this.cleanup()\n\n if (!scrollElement) {\n this.maybeNotify()\n return\n }\n\n this.scrollElement = scrollElement\n\n if (this.scrollElement && 'ownerDocument' in this.scrollElement) {\n this.targetWindow = this.scrollElement.ownerDocument.defaultView\n } else {\n this.targetWindow = this.scrollElement?.window ?? null\n }\n\n this.elementsCache.forEach((cached) => {\n this.observer.observe(cached)\n })\n\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: undefined,\n behavior: undefined,\n })\n\n this.unsubs.push(\n this.options.observeElementRect(this, (rect) => {\n this.scrollRect = rect\n this.maybeNotify()\n }),\n )\n\n this.unsubs.push(\n this.options.observeElementOffset(this, (offset, isScrolling) => {\n this.scrollAdjustments = 0\n this.scrollDirection = isScrolling\n ? this.getScrollOffset() < offset\n ? 'forward'\n : 'backward'\n : null\n this.scrollOffset = offset\n this.isScrolling = isScrolling\n\n this.maybeNotify()\n }),\n )\n }\n }\n\n private getSize = () => {\n if (!this.options.enabled) {\n this.scrollRect = null\n return 0\n }\n\n this.scrollRect = this.scrollRect ?? this.options.initialRect\n\n return this.scrollRect[this.options.horizontal ? 'width' : 'height']\n }\n\n private getScrollOffset = () => {\n if (!this.options.enabled) {\n this.scrollOffset = null\n return 0\n }\n\n this.scrollOffset =\n this.scrollOffset ??\n (typeof this.options.initialOffset === 'function'\n ? this.options.initialOffset()\n : this.options.initialOffset)\n\n return this.scrollOffset\n }\n\n private getFurthestMeasurement = (\n measurements: Array,\n index: number,\n ) => {\n const furthestMeasurementsFound = new Map()\n const furthestMeasurements = new Map()\n for (let m = index - 1; m >= 0; m--) {\n const measurement = measurements[m]!\n\n if (furthestMeasurementsFound.has(measurement.lane)) {\n continue\n }\n\n const previousFurthestMeasurement = furthestMeasurements.get(\n measurement.lane,\n )\n if (\n previousFurthestMeasurement == null ||\n measurement.end > previousFurthestMeasurement.end\n ) {\n furthestMeasurements.set(measurement.lane, measurement)\n } else if (measurement.end < previousFurthestMeasurement.end) {\n furthestMeasurementsFound.set(measurement.lane, true)\n }\n\n if (furthestMeasurementsFound.size === this.options.lanes) {\n break\n }\n }\n\n return furthestMeasurements.size === this.options.lanes\n ? Array.from(furthestMeasurements.values()).sort((a, b) => {\n if (a.end === b.end) {\n return a.index - b.index\n }\n\n return a.end - b.end\n })[0]\n : undefined\n }\n\n private getMeasurementOptions = memo(\n () => [\n this.options.count,\n this.options.paddingStart,\n this.options.scrollMargin,\n this.options.getItemKey,\n this.options.enabled,\n ],\n (count, paddingStart, scrollMargin, getItemKey, enabled) => {\n this.pendingMeasuredCacheIndexes = []\n return {\n count,\n paddingStart,\n scrollMargin,\n getItemKey,\n enabled,\n }\n },\n {\n key: false,\n },\n )\n\n private getMeasurements = memo(\n () => [this.getMeasurementOptions(), this.itemSizeCache],\n (\n { count, paddingStart, scrollMargin, getItemKey, enabled },\n itemSizeCache,\n ) => {\n if (!enabled) {\n this.measurementsCache = []\n this.itemSizeCache.clear()\n return []\n }\n\n if (this.measurementsCache.length === 0) {\n this.measurementsCache = this.options.initialMeasurementsCache\n this.measurementsCache.forEach((item) => {\n this.itemSizeCache.set(item.key, item.size)\n })\n }\n\n const min =\n this.pendingMeasuredCacheIndexes.length > 0\n ? Math.min(...this.pendingMeasuredCacheIndexes)\n : 0\n this.pendingMeasuredCacheIndexes = []\n\n const measurements = this.measurementsCache.slice(0, min)\n\n for (let i = min; i < count; i++) {\n const key = getItemKey(i)\n\n const furthestMeasurement =\n this.options.lanes === 1\n ? measurements[i - 1]\n : this.getFurthestMeasurement(measurements, i)\n\n const start = furthestMeasurement\n ? furthestMeasurement.end + this.options.gap\n : paddingStart + scrollMargin\n\n const measuredSize = itemSizeCache.get(key)\n const size =\n typeof measuredSize === 'number'\n ? measuredSize\n : this.options.estimateSize(i)\n\n const end = start + size\n\n const lane = furthestMeasurement\n ? furthestMeasurement.lane\n : i % this.options.lanes\n\n measurements[i] = {\n index: i,\n start,\n size,\n end,\n key,\n lane,\n }\n }\n\n this.measurementsCache = measurements\n\n return measurements\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getMeasurements',\n debug: () => this.options.debug,\n },\n )\n\n calculateRange = memo(\n () => [this.getMeasurements(), this.getSize(), this.getScrollOffset()],\n (measurements, outerSize, scrollOffset) => {\n return (this.range =\n measurements.length > 0 && outerSize > 0\n ? calculateRange({\n measurements,\n outerSize,\n scrollOffset,\n })\n : null)\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'calculateRange',\n debug: () => this.options.debug,\n },\n )\n\n private getIndexes = memo(\n () => [\n this.options.rangeExtractor,\n this.calculateRange(),\n this.options.overscan,\n this.options.count,\n ],\n (rangeExtractor, range, overscan, count) => {\n return range === null\n ? []\n : rangeExtractor({\n startIndex: range.startIndex,\n endIndex: range.endIndex,\n overscan,\n count,\n })\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getIndexes',\n debug: () => this.options.debug,\n },\n )\n\n indexFromElement = (node: TItemElement) => {\n const attributeName = this.options.indexAttribute\n const indexStr = node.getAttribute(attributeName)\n\n if (!indexStr) {\n console.warn(\n `Missing attribute name '${attributeName}={index}' on measured element.`,\n )\n return -1\n }\n\n return parseInt(indexStr, 10)\n }\n\n private _measureElement = (\n node: TItemElement,\n entry: ResizeObserverEntry | undefined,\n ) => {\n const index = this.indexFromElement(node)\n const item = this.measurementsCache[index]\n if (!item) {\n return\n }\n const key = item.key\n const prevNode = this.elementsCache.get(key)\n\n if (prevNode !== node) {\n if (prevNode) {\n this.observer.unobserve(prevNode)\n }\n this.observer.observe(node)\n this.elementsCache.set(key, node)\n }\n\n if (node.isConnected) {\n this.resizeItem(index, this.options.measureElement(node, entry, this))\n }\n }\n\n resizeItem = (index: number, size: number) => {\n const item = this.measurementsCache[index]\n if (!item) {\n return\n }\n const itemSize = this.itemSizeCache.get(item.key) ?? item.size\n const delta = size - itemSize\n\n if (delta !== 0) {\n if (\n this.shouldAdjustScrollPositionOnItemSizeChange !== undefined\n ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this)\n : item.start < this.getScrollOffset() + this.scrollAdjustments\n ) {\n if (process.env.NODE_ENV !== 'production' && this.options.debug) {\n console.info('correction', delta)\n }\n\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: (this.scrollAdjustments += delta),\n behavior: undefined,\n })\n }\n\n this.pendingMeasuredCacheIndexes.push(item.index)\n this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size))\n\n this.notify(false)\n }\n }\n\n measureElement = (node: TItemElement | null | undefined) => {\n if (!node) {\n this.elementsCache.forEach((cached, key) => {\n if (!cached.isConnected) {\n this.observer.unobserve(cached)\n this.elementsCache.delete(key)\n }\n })\n return\n }\n\n this._measureElement(node, undefined)\n }\n\n getVirtualItems = memo(\n () => [this.getIndexes(), this.getMeasurements()],\n (indexes, measurements) => {\n const virtualItems: Array = []\n\n for (let k = 0, len = indexes.length; k < len; k++) {\n const i = indexes[k]!\n const measurement = measurements[i]!\n\n virtualItems.push(measurement)\n }\n\n return virtualItems\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getVirtualItems',\n debug: () => this.options.debug,\n },\n )\n\n getVirtualItemForOffset = (offset: number) => {\n const measurements = this.getMeasurements()\n if (measurements.length === 0) {\n return undefined\n }\n return notUndefined(\n measurements[\n findNearestBinarySearch(\n 0,\n measurements.length - 1,\n (index: number) => notUndefined(measurements[index]).start,\n offset,\n )\n ],\n )\n }\n\n getOffsetForAlignment = (toOffset: number, align: ScrollAlignment) => {\n const size = this.getSize()\n const scrollOffset = this.getScrollOffset()\n\n if (align === 'auto') {\n if (toOffset <= scrollOffset) {\n align = 'start'\n } else if (toOffset >= scrollOffset + size) {\n align = 'end'\n } else {\n align = 'start'\n }\n }\n\n if (align === 'start') {\n toOffset = toOffset\n } else if (align === 'end') {\n toOffset = toOffset - size\n } else if (align === 'center') {\n toOffset = toOffset - size / 2\n }\n\n const scrollSizeProp = this.options.horizontal\n ? 'scrollWidth'\n : 'scrollHeight'\n const scrollSize = this.scrollElement\n ? 'document' in this.scrollElement\n ? this.scrollElement.document.documentElement[scrollSizeProp]\n : this.scrollElement[scrollSizeProp]\n : 0\n\n const maxOffset = scrollSize - size\n\n return Math.max(Math.min(maxOffset, toOffset), 0)\n }\n\n getOffsetForIndex = (index: number, align: ScrollAlignment = 'auto') => {\n index = Math.max(0, Math.min(index, this.options.count - 1))\n\n const item = this.measurementsCache[index]\n if (!item) {\n return undefined\n }\n\n const size = this.getSize()\n const scrollOffset = this.getScrollOffset()\n\n if (align === 'auto') {\n if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {\n align = 'end'\n } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {\n align = 'start'\n } else {\n return [scrollOffset, align] as const\n }\n }\n\n const toOffset =\n align === 'end'\n ? item.end + this.options.scrollPaddingEnd\n : item.start - this.options.scrollPaddingStart\n\n return [this.getOffsetForAlignment(toOffset, align), align] as const\n }\n\n private isDynamicMode = () => this.elementsCache.size > 0\n\n private cancelScrollToIndex = () => {\n if (this.scrollToIndexTimeoutId !== null && this.targetWindow) {\n this.targetWindow.clearTimeout(this.scrollToIndexTimeoutId)\n this.scrollToIndexTimeoutId = null\n }\n }\n\n scrollToOffset = (\n toOffset: number,\n { align = 'start', behavior }: ScrollToOffsetOptions = {},\n ) => {\n this.cancelScrollToIndex()\n\n if (behavior === 'smooth' && this.isDynamicMode()) {\n console.warn(\n 'The `smooth` scroll behavior is not fully supported with dynamic size.',\n )\n }\n\n this._scrollToOffset(this.getOffsetForAlignment(toOffset, align), {\n adjustments: undefined,\n behavior,\n })\n }\n\n scrollToIndex = (\n index: number,\n { align: initialAlign = 'auto', behavior }: ScrollToIndexOptions = {},\n ) => {\n index = Math.max(0, Math.min(index, this.options.count - 1))\n\n this.cancelScrollToIndex()\n\n if (behavior === 'smooth' && this.isDynamicMode()) {\n console.warn(\n 'The `smooth` scroll behavior is not fully supported with dynamic size.',\n )\n }\n\n const offsetAndAlign = this.getOffsetForIndex(index, initialAlign)\n if (!offsetAndAlign) return\n\n const [offset, align] = offsetAndAlign\n\n this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n if (behavior !== 'smooth' && this.isDynamicMode() && this.targetWindow) {\n this.scrollToIndexTimeoutId = this.targetWindow.setTimeout(() => {\n this.scrollToIndexTimeoutId = null\n\n const elementInDOM = this.elementsCache.has(\n this.options.getItemKey(index),\n )\n\n if (elementInDOM) {\n const [latestOffset] = notUndefined(\n this.getOffsetForIndex(index, align),\n )\n\n if (!approxEqual(latestOffset, this.getScrollOffset())) {\n this.scrollToIndex(index, { align, behavior })\n }\n } else {\n this.scrollToIndex(index, { align, behavior })\n }\n })\n }\n }\n\n scrollBy = (delta: number, { behavior }: ScrollToOffsetOptions = {}) => {\n this.cancelScrollToIndex()\n\n if (behavior === 'smooth' && this.isDynamicMode()) {\n console.warn(\n 'The `smooth` scroll behavior is not fully supported with dynamic size.',\n )\n }\n\n this._scrollToOffset(this.getScrollOffset() + delta, {\n adjustments: undefined,\n behavior,\n })\n }\n\n getTotalSize = () => {\n const measurements = this.getMeasurements()\n\n let end: number\n // If there are no measurements, set the end to paddingStart\n if (measurements.length === 0) {\n end = this.options.paddingStart\n } else {\n // If lanes is 1, use the last measurement's end, otherwise find the maximum end value among all measurements\n end =\n this.options.lanes === 1\n ? (measurements[measurements.length - 1]?.end ?? 0)\n : Math.max(\n ...measurements.slice(-this.options.lanes).map((m) => m.end),\n )\n }\n\n return Math.max(\n end - this.options.scrollMargin + this.options.paddingEnd,\n 0,\n )\n }\n\n private _scrollToOffset = (\n offset: number,\n {\n adjustments,\n behavior,\n }: {\n adjustments: number | undefined\n behavior: ScrollBehavior | undefined\n },\n ) => {\n this.options.scrollToFn(offset, { behavior, adjustments }, this)\n }\n\n measure = () => {\n this.itemSizeCache = new Map()\n this.notify(false)\n }\n}\n\nconst findNearestBinarySearch = (\n low: number,\n high: number,\n getCurrentValue: (i: number) => number,\n value: number,\n) => {\n while (low <= high) {\n const middle = ((low + high) / 2) | 0\n const currentValue = getCurrentValue(middle)\n\n if (currentValue < value) {\n low = middle + 1\n } else if (currentValue > value) {\n high = middle - 1\n } else {\n return middle\n }\n }\n\n if (low > 0) {\n return low - 1\n } else {\n return 0\n }\n}\n\nfunction calculateRange({\n measurements,\n outerSize,\n scrollOffset,\n}: {\n measurements: Array\n outerSize: number\n scrollOffset: number\n}) {\n const count = measurements.length - 1\n const getOffset = (index: number) => measurements[index]!.start\n\n const startIndex = findNearestBinarySearch(0, count, getOffset, scrollOffset)\n let endIndex = startIndex\n\n while (\n endIndex < count &&\n measurements[endIndex]!.end < scrollOffset + outerSize\n ) {\n endIndex++\n }\n\n return { startIndex, endIndex }\n}\n","import * as React from 'react'\nimport { flushSync } from 'react-dom'\nimport {\n Virtualizer,\n elementScroll,\n observeElementOffset,\n observeElementRect,\n observeWindowOffset,\n observeWindowRect,\n windowScroll,\n} from '@tanstack/virtual-core'\nimport type { PartialKeys, VirtualizerOptions } from '@tanstack/virtual-core'\n\nexport * from '@tanstack/virtual-core'\n\nconst useIsomorphicLayoutEffect =\n typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nfunction useVirtualizerBase<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n>(\n options: VirtualizerOptions,\n): Virtualizer {\n const rerender = React.useReducer(() => ({}), {})[1]\n\n const resolvedOptions: VirtualizerOptions = {\n ...options,\n onChange: (instance, sync) => {\n if (sync) {\n flushSync(rerender)\n } else {\n rerender()\n }\n options.onChange?.(instance, sync)\n },\n }\n\n const [instance] = React.useState(\n () => new Virtualizer(resolvedOptions),\n )\n\n instance.setOptions(resolvedOptions)\n\n React.useEffect(() => {\n return instance._didMount()\n }, [])\n\n useIsomorphicLayoutEffect(() => {\n return instance._willUpdate()\n })\n\n return instance\n}\n\nexport function useVirtualizer<\n TScrollElement extends Element,\n TItemElement extends Element,\n>(\n options: PartialKeys<\n VirtualizerOptions,\n 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'\n >,\n): Virtualizer {\n return useVirtualizerBase({\n observeElementRect: observeElementRect,\n observeElementOffset: observeElementOffset,\n scrollToFn: elementScroll,\n ...options,\n })\n}\n\nexport function useWindowVirtualizer(\n options: PartialKeys<\n VirtualizerOptions,\n | 'getScrollElement'\n | 'observeElementRect'\n | 'observeElementOffset'\n | 'scrollToFn'\n >,\n): Virtualizer {\n return useVirtualizerBase({\n getScrollElement: () => (typeof document !== 'undefined' ? window : null),\n observeElementRect: observeWindowRect,\n observeElementOffset: observeWindowOffset,\n scrollToFn: windowScroll,\n initialOffset: () => (typeof document !== 'undefined' ? window.scrollY : 0),\n ...options,\n })\n}\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h5c.55 0 1-.45 1-1s-.45-1-1-1H5c-1.11 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6c0-.55-.45-1-1-1s-1 .45-1 1v5c0 .55-.45 1-1 1M14 4c0 .55.45 1 1 1h2.59l-9.13 9.13c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L19 6.41V9c0 .55.45 1 1 1s1-.45 1-1V4c0-.55-.45-1-1-1h-5c-.55 0-1 .45-1 1\"\n}), 'OpenInNewRounded');","import ownerWindow from '@mui/utils/ownerWindow';\nexport default ownerWindow;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"addEndListener\", \"appear\", \"children\", \"container\", \"direction\", \"easing\", \"in\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"style\", \"timeout\", \"TransitionComponent\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { Transition } from 'react-transition-group';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport HTMLElementType from '@mui/utils/HTMLElementType';\nimport elementAcceptingRef from '@mui/utils/elementAcceptingRef';\nimport debounce from '../utils/debounce';\nimport useForkRef from '../utils/useForkRef';\nimport useTheme from '../styles/useTheme';\nimport { reflow, getTransitionProps } from '../transitions/utils';\nimport { ownerWindow } from '../utils';\n\n// Translate the node so it can't be seen on the screen.\n// Later, we're going to translate the node back to its original location with `none`.\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction getTranslateValue(direction, node, resolvedContainer) {\n const rect = node.getBoundingClientRect();\n const containerRect = resolvedContainer && resolvedContainer.getBoundingClientRect();\n const containerWindow = ownerWindow(node);\n let transform;\n if (node.fakeTransform) {\n transform = node.fakeTransform;\n } else {\n const computedStyle = containerWindow.getComputedStyle(node);\n transform = computedStyle.getPropertyValue('-webkit-transform') || computedStyle.getPropertyValue('transform');\n }\n let offsetX = 0;\n let offsetY = 0;\n if (transform && transform !== 'none' && typeof transform === 'string') {\n const transformValues = transform.split('(')[1].split(')')[0].split(',');\n offsetX = parseInt(transformValues[4], 10);\n offsetY = parseInt(transformValues[5], 10);\n }\n if (direction === 'left') {\n if (containerRect) {\n return `translateX(${containerRect.right + offsetX - rect.left}px)`;\n }\n return `translateX(${containerWindow.innerWidth + offsetX - rect.left}px)`;\n }\n if (direction === 'right') {\n if (containerRect) {\n return `translateX(-${rect.right - containerRect.left - offsetX}px)`;\n }\n return `translateX(-${rect.left + rect.width - offsetX}px)`;\n }\n if (direction === 'up') {\n if (containerRect) {\n return `translateY(${containerRect.bottom + offsetY - rect.top}px)`;\n }\n return `translateY(${containerWindow.innerHeight + offsetY - rect.top}px)`;\n }\n\n // direction === 'down'\n if (containerRect) {\n return `translateY(-${rect.top - containerRect.top + rect.height - offsetY}px)`;\n }\n return `translateY(-${rect.top + rect.height - offsetY}px)`;\n}\nfunction resolveContainer(containerPropProp) {\n return typeof containerPropProp === 'function' ? containerPropProp() : containerPropProp;\n}\nexport function setTranslateValue(direction, node, containerProp) {\n const resolvedContainer = resolveContainer(containerProp);\n const transform = getTranslateValue(direction, node, resolvedContainer);\n if (transform) {\n node.style.webkitTransform = transform;\n node.style.transform = transform;\n }\n}\n\n/**\n * The Slide transition is used by the [Drawer](/material-ui/react-drawer/) component.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\nconst Slide = /*#__PURE__*/React.forwardRef(function Slide(props, ref) {\n const theme = useTheme();\n const defaultEasing = {\n enter: theme.transitions.easing.easeOut,\n exit: theme.transitions.easing.sharp\n };\n const defaultTimeout = {\n enter: theme.transitions.duration.enteringScreen,\n exit: theme.transitions.duration.leavingScreen\n };\n const {\n addEndListener,\n appear = true,\n children,\n container: containerProp,\n direction = 'down',\n easing: easingProp = defaultEasing,\n in: inProp,\n onEnter,\n onEntered,\n onEntering,\n onExit,\n onExited,\n onExiting,\n style,\n timeout = defaultTimeout,\n // eslint-disable-next-line react/prop-types\n TransitionComponent = Transition\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const childrenRef = React.useRef(null);\n const handleRef = useForkRef(children.ref, childrenRef, ref);\n const normalizedTransitionCallback = callback => isAppearing => {\n if (callback) {\n // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n if (isAppearing === undefined) {\n callback(childrenRef.current);\n } else {\n callback(childrenRef.current, isAppearing);\n }\n }\n };\n const handleEnter = normalizedTransitionCallback((node, isAppearing) => {\n setTranslateValue(direction, node, containerProp);\n reflow(node);\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n const handleEntering = normalizedTransitionCallback((node, isAppearing) => {\n const transitionProps = getTransitionProps({\n timeout,\n style,\n easing: easingProp\n }, {\n mode: 'enter'\n });\n node.style.webkitTransition = theme.transitions.create('-webkit-transform', _extends({}, transitionProps));\n node.style.transition = theme.transitions.create('transform', _extends({}, transitionProps));\n node.style.webkitTransform = 'none';\n node.style.transform = 'none';\n if (onEntering) {\n onEntering(node, isAppearing);\n }\n });\n const handleEntered = normalizedTransitionCallback(onEntered);\n const handleExiting = normalizedTransitionCallback(onExiting);\n const handleExit = normalizedTransitionCallback(node => {\n const transitionProps = getTransitionProps({\n timeout,\n style,\n easing: easingProp\n }, {\n mode: 'exit'\n });\n node.style.webkitTransition = theme.transitions.create('-webkit-transform', transitionProps);\n node.style.transition = theme.transitions.create('transform', transitionProps);\n setTranslateValue(direction, node, containerProp);\n if (onExit) {\n onExit(node);\n }\n });\n const handleExited = normalizedTransitionCallback(node => {\n // No need for transitions when the component is hidden\n node.style.webkitTransition = '';\n node.style.transition = '';\n if (onExited) {\n onExited(node);\n }\n });\n const handleAddEndListener = next => {\n if (addEndListener) {\n // Old call signature before `react-transition-group` implemented `nodeRef`\n addEndListener(childrenRef.current, next);\n }\n };\n const updatePosition = React.useCallback(() => {\n if (childrenRef.current) {\n setTranslateValue(direction, childrenRef.current, containerProp);\n }\n }, [direction, containerProp]);\n React.useEffect(() => {\n // Skip configuration where the position is screen size invariant.\n if (inProp || direction === 'down' || direction === 'right') {\n return undefined;\n }\n const handleResize = debounce(() => {\n if (childrenRef.current) {\n setTranslateValue(direction, childrenRef.current, containerProp);\n }\n });\n const containerWindow = ownerWindow(childrenRef.current);\n containerWindow.addEventListener('resize', handleResize);\n return () => {\n handleResize.clear();\n containerWindow.removeEventListener('resize', handleResize);\n };\n }, [direction, inProp, containerProp]);\n React.useEffect(() => {\n if (!inProp) {\n // We need to update the position of the drawer when the direction change and\n // when it's hidden.\n updatePosition();\n }\n }, [inProp, updatePosition]);\n return /*#__PURE__*/_jsx(TransitionComponent, _extends({\n nodeRef: childrenRef,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: handleAddEndListener,\n appear: appear,\n in: inProp,\n timeout: timeout\n }, other, {\n children: (state, childProps) => {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n ref: handleRef,\n style: _extends({\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined\n }, style, children.props.style)\n }, childProps));\n }\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Slide.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Add a custom transition end trigger. Called with the transitioning DOM\n * node and a done callback. Allows for more fine grained transition end\n * logic. Note: Timeouts are still used as a fallback if provided.\n */\n addEndListener: PropTypes.func,\n /**\n * Perform the enter transition when it first mounts if `in` is also `true`.\n * Set this to `false` to disable this behavior.\n * @default true\n */\n appear: PropTypes.bool,\n /**\n * A single child content element.\n */\n children: elementAcceptingRef.isRequired,\n /**\n * An HTML element, or a function that returns one.\n * It's used to set the container the Slide is transitioning from.\n */\n container: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.func]), props => {\n if (props.open) {\n const resolvedContainer = resolveContainer(props.container);\n if (resolvedContainer && resolvedContainer.nodeType === 1) {\n const box = resolvedContainer.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['MUI: The `container` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else if (!resolvedContainer || typeof resolvedContainer.getBoundingClientRect !== 'function' || resolvedContainer.contextElement != null && resolvedContainer.contextElement.nodeType !== 1) {\n return new Error(['MUI: The `container` prop provided to the component is invalid.', 'It should be an HTML element instance.'].join('\\n'));\n }\n }\n return null;\n }),\n /**\n * Direction the child node will enter from.\n * @default 'down'\n */\n direction: PropTypes.oneOf(['down', 'left', 'right', 'up']),\n /**\n * The transition timing function.\n * You may specify a single easing or a object containing enter and exit values.\n * @default {\n * enter: theme.transitions.easing.easeOut,\n * exit: theme.transitions.easing.sharp,\n * }\n */\n easing: PropTypes.oneOfType([PropTypes.shape({\n enter: PropTypes.string,\n exit: PropTypes.string\n }), PropTypes.string]),\n /**\n * If `true`, the component will transition in.\n */\n in: PropTypes.bool,\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n * @default {\n * enter: theme.transitions.duration.enteringScreen,\n * exit: theme.transitions.duration.leavingScreen,\n * }\n */\n timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nexport default Slide;","export const defaultMaxHeight = 686;\n\nexport const lifiExplorerUrl = 'https://scan.li.fi';\n","import type { Chain } from '@lifi/sdk';\nimport { lifiExplorerUrl } from '../config/constants.js';\nimport { useAvailableChains } from '../hooks/useAvailableChains.js';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\n\nconst sanitiseBaseUrl = (baseUrl: string) => baseUrl.trim().replace(/\\/+$/, '');\n\nexport type TransactionLinkProps = { chain?: Chain | number } & (\n | {\n txHash: string;\n txLink?: never;\n }\n | {\n txHash?: never;\n txLink: string;\n }\n);\n\nexport const useExplorer = () => {\n const { explorerUrls } = useWidgetConfig();\n const { getChainById } = useAvailableChains();\n\n const getBaseUrl = (chain: Chain) => {\n const baseUrl = explorerUrls?.[chain.id]\n ? explorerUrls[chain.id][0]\n : chain.metamask.blockExplorerUrls[0];\n\n return sanitiseBaseUrl(baseUrl);\n };\n\n const resolveChain = (chain: Chain | number) =>\n Number.isFinite(chain) ? getChainById(chain as number) : (chain as Chain);\n\n const getTransactionLink = ({\n txHash,\n txLink,\n chain,\n }: TransactionLinkProps) => {\n if (!txHash && txLink) {\n return txLink;\n }\n if (!chain) {\n const baseUrl = explorerUrls?.internal?.[0]\n ? sanitiseBaseUrl(explorerUrls?.internal[0])\n : lifiExplorerUrl;\n return `${baseUrl}/tx/${txHash}`;\n }\n const resolvedChain = resolveChain(chain);\n return `${resolvedChain ? getBaseUrl(resolvedChain) : lifiExplorerUrl}/tx/${txHash}`;\n };\n\n const getAddressLink = (address: string, chain?: Chain | number) => {\n if (!chain) {\n const baseUrl = explorerUrls?.internal?.[0]\n ? sanitiseBaseUrl(explorerUrls?.internal[0])\n : lifiExplorerUrl;\n return `${baseUrl}/address/${address}`;\n }\n\n const resolvedChain = resolveChain(chain);\n return `${resolvedChain ? getBaseUrl(resolvedChain) : lifiExplorerUrl}/address/${address}`;\n };\n\n return {\n getTransactionLink,\n getAddressLink,\n };\n};\n","import { styled } from '@mui/material';\nimport { ListItemButton as ListItemButtonBase } from '../ListItemButton.js';\n\nexport const ListItemButton = styled(ListItemButtonBase)(({ theme }) => ({\n paddingLeft: theme.spacing(1.5),\n paddingRight: theme.spacing(1.5),\n height: 64,\n width: '100%',\n}));\n","import {\n ListItem as MuiListItem,\n listItemSecondaryActionClasses,\n listItemTextClasses,\n styled,\n} from '@mui/material';\n\nexport const ListItem = styled(MuiListItem)(({ theme }) => ({\n height: 64,\n flexDirection: 'column',\n alignItems: 'flex-start',\n padding: theme.spacing(0, 1.5),\n [`.${listItemSecondaryActionClasses.root}`]: {\n right: theme.spacing(3),\n },\n [`& .${listItemTextClasses.secondary}`]: {\n fontSize: 12,\n fontWeight: 500,\n },\n [`& .${listItemTextClasses.primary}, & .${listItemTextClasses.secondary}`]: {\n lineHeight: 1.3334,\n textOverflow: 'ellipsis',\n overflow: 'hidden',\n whiteSpace: 'nowrap',\n },\n}));\n","import type { IconButtonProps, LinkProps } from '@mui/material';\nimport { IconButton as MuiIconButton, styled } from '@mui/material';\nimport { getContrastAlphaColor } from '../../utils/colors.js';\nimport { ListItem as ListItemBase } from '../ListItem/ListItem.js';\n\nexport const ListItem = styled(ListItemBase)(({ theme }) => ({\n position: 'absolute',\n top: 0,\n left: 0,\n}));\n\nexport const IconButton = styled(MuiIconButton)(\n ({ theme }) => ({\n lineHeight: 1,\n fontSize: 12,\n fontWeight: 400,\n padding: theme.spacing(0.375, 0.375),\n margin: theme.spacing(0, 0, 0, 0.25),\n color: 'inherit',\n backgroundColor: 'unset',\n minWidth: 'unset',\n borderRadius: theme.shape.borderRadiusTertiary,\n '&:hover': {\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n },\n svg: {\n fontSize: 14,\n },\n }),\n);\n","import { OpenInNewRounded } from '@mui/icons-material';\nimport {\n Avatar,\n Box,\n Link,\n ListItemAvatar,\n ListItemText,\n Skeleton,\n Slide,\n Typography,\n} from '@mui/material';\nimport type { MouseEventHandler } from 'react';\nimport { useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { formatUnits } from 'viem';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { formatTokenAmount, formatTokenPrice } from '../../utils/format.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { ListItemButton } from '../ListItem/ListItemButton.js';\nimport { IconButton, ListItem } from './TokenList.style.js';\nimport type { TokenListItemButtonProps, TokenListItemProps } from './types.js';\n\nexport const TokenListItem: React.FC = ({\n onClick,\n size,\n start,\n token,\n chain,\n showBalance,\n isBalanceLoading,\n startAdornment,\n endAdornment,\n}) => {\n const handleClick: MouseEventHandler = (e) => {\n e.stopPropagation();\n onClick?.(token.address);\n };\n return (\n \n {startAdornment}\n \n {endAdornment}\n \n );\n};\n\nexport const TokenListItemButton: React.FC = ({\n onClick,\n token,\n chain,\n showBalance,\n isBalanceLoading,\n}) => {\n const { t } = useTranslation();\n const { getAddressLink } = useExplorer();\n\n const tokenPrice = token.amount\n ? formatTokenPrice(\n formatUnits(token.amount, token.decimals),\n token.priceUSD,\n )\n : undefined;\n const container = useRef(null);\n const timeoutId = useRef>();\n const [showAddress, setShowAddress] = useState(false);\n\n const onMouseEnter = () => {\n timeoutId.current = setTimeout(() => setShowAddress(true), 350);\n };\n\n const onMouseLeave = () => {\n clearTimeout(timeoutId.current);\n if (showAddress) {\n setShowAddress(false);\n }\n };\n\n return (\n \n \n \n {token.symbol?.[0]}\n \n \n \n \n {token.name}\n \n \n \n \n {shortenAddress(token.address)}\n \n e.stopPropagation()}\n >\n \n \n \n \n \n }\n />\n {showBalance ? (\n isBalanceLoading ? (\n \n ) : (\n \n {token.amount ? (\n \n {t('format.number', {\n value: formatTokenAmount(token.amount, token.decimals),\n })}\n \n ) : null}\n {tokenPrice ? (\n \n {t(`format.currency`, {\n value: tokenPrice,\n })}\n \n ) : null}\n \n )\n ) : null}\n \n );\n};\n\nexport const TokenListItemSkeleton = () => {\n return (\n }\n disablePadding\n sx={{ position: 'relative', flexDirection: 'row', alignItems: 'center' }}\n >\n \n \n \n }\n secondary={}\n />\n \n );\n};\n\nexport const TokenAmountSkeleton: React.FC = () => {\n return (\n \n \n \n \n );\n};\n","import { List, Typography } from '@mui/material';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport type { FC } from 'react';\nimport { useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport type { TokenAmount } from '../../types/token.js';\nimport { TokenListItem, TokenListItemSkeleton } from './TokenListItem.js';\nimport type { VirtualizedTokenListProps } from './types.js';\n\nexport const VirtualizedTokenList: FC = ({\n account,\n tokens,\n scrollElementRef,\n chainId,\n chain,\n isLoading,\n isBalanceLoading,\n showCategories,\n onClick,\n}) => {\n const { t } = useTranslation();\n\n const { getVirtualItems, getTotalSize, scrollToIndex } = useVirtualizer({\n count: tokens.length,\n overscan: 10,\n paddingEnd: 12,\n getScrollElement: () => scrollElementRef.current,\n estimateSize: (index) => {\n // Base size for TokenListItem\n let size = 64;\n // Early return if categories are not shown\n if (!showCategories) {\n return size;\n }\n\n const currentToken = tokens[index];\n const previousToken = tokens[index - 1];\n\n // Adjust size for the first featured token\n if (currentToken.featured && index === 0) {\n size += 24;\n }\n\n // Adjust size based on changes between the current and previous tokens\n const isCategoryChanged =\n (previousToken?.amount && !currentToken.amount) ||\n (previousToken?.featured && !currentToken.featured) ||\n (previousToken?.popular && !currentToken.popular);\n\n if (isCategoryChanged) {\n size += 32;\n }\n\n return size;\n },\n getItemKey: (index) => `${tokens[index].address}-${index}`,\n });\n\n useEffect(() => {\n // Scroll to the top of the list when switching the chains\n if (getVirtualItems().length) {\n scrollToIndex(0, { align: 'start' });\n }\n }, [scrollToIndex, chainId, getVirtualItems]);\n\n if (isLoading) {\n return (\n \n {Array.from({ length: 3 }).map((_, index) => (\n // eslint-disable-next-line react/no-array-index-key\n \n ))}\n \n );\n }\n\n return (\n \n {getVirtualItems().map((item) => {\n const currentToken = tokens[item.index];\n const previousToken: TokenAmount | undefined = tokens[item.index - 1];\n\n const isFirstFeaturedToken = currentToken.featured && item.index === 0;\n\n const isTransitionFromFeaturedTokens =\n previousToken?.featured && !currentToken.featured;\n\n const isTransitionFromMyTokens =\n previousToken?.amount && !currentToken.amount;\n\n const isTransitionToMyTokens =\n isTransitionFromFeaturedTokens && currentToken.amount;\n\n const isTransitionToPopularTokens =\n (isTransitionFromFeaturedTokens || isTransitionFromMyTokens) &&\n currentToken.popular;\n\n const shouldShowAllTokensCategory =\n isTransitionFromMyTokens ||\n isTransitionFromFeaturedTokens ||\n (previousToken?.popular && !currentToken.popular);\n\n const startAdornmentLabel = showCategories\n ? (() => {\n if (isFirstFeaturedToken) {\n return t('main.featuredTokens');\n }\n if (isTransitionToMyTokens) {\n return t('main.myTokens');\n }\n if (isTransitionToPopularTokens) {\n return t('main.popularTokens');\n }\n if (shouldShowAllTokensCategory) {\n return t('main.allTokens');\n }\n return null;\n })()\n : null;\n\n return (\n \n {startAdornmentLabel}\n \n ) : null\n }\n />\n );\n })}\n \n );\n};\n","import { Box } from '@mui/material';\nimport type { FC } from 'react';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useChain } from '../../hooks/useChain.js';\nimport { useDebouncedWatch } from '../../hooks/useDebouncedWatch.js';\nimport { useTokenBalances } from '../../hooks/useTokenBalances.js';\nimport { useTokenSearch } from '../../hooks/useTokenSearch.js';\nimport { FormKeyHelper } from '../../stores/form/types.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport type { TokenAmount } from '../../types/token.js';\nimport { TokenNotFound } from './TokenNotFound.js';\nimport { VirtualizedTokenList } from './VirtualizedTokenList.js';\nimport type { TokenListProps } from './types.js';\nimport { useTokenSelect } from './useTokenSelect.js';\nimport { filteredTokensComparator } from './utils.js';\n\nexport const TokenList: FC = ({\n formType,\n parentRef,\n height,\n onClick,\n}) => {\n const [selectedChainId] = useFieldValues(FormKeyHelper.getChainKey(formType));\n const [tokenSearchFilter]: string[] = useDebouncedWatch(\n 320,\n 'tokenSearchFilter',\n );\n\n const { chain, isLoading: isChainLoading } = useChain(selectedChainId);\n const { account } = useAccount({ chainType: chain?.chainType });\n\n const {\n tokens: chainTokens,\n tokensWithBalance,\n isLoading: isTokensLoading,\n isBalanceLoading,\n featuredTokens,\n popularTokens,\n } = useTokenBalances(selectedChainId);\n\n let filteredTokens = (tokensWithBalance ??\n chainTokens ??\n []) as TokenAmount[];\n const normalizedSearchFilter = tokenSearchFilter?.replaceAll('$', '');\n const searchFilter = normalizedSearchFilter?.toUpperCase() ?? '';\n\n filteredTokens = tokenSearchFilter\n ? filteredTokens\n .filter(\n (token) =>\n token.name?.toUpperCase().includes(searchFilter) ||\n token.symbol.toUpperCase().includes(searchFilter) ||\n token.address.toUpperCase().includes(searchFilter),\n )\n .sort(filteredTokensComparator(searchFilter))\n : filteredTokens;\n\n const tokenSearchEnabled =\n !isTokensLoading &&\n !filteredTokens.length &&\n !!tokenSearchFilter &&\n !!selectedChainId;\n\n const { token: searchedToken, isLoading: isSearchedTokenLoading } =\n useTokenSearch(selectedChainId, normalizedSearchFilter, tokenSearchEnabled);\n\n const isLoading =\n isTokensLoading ||\n isChainLoading ||\n (tokenSearchEnabled && isSearchedTokenLoading);\n\n const tokens = filteredTokens.length\n ? filteredTokens\n : searchedToken\n ? [searchedToken]\n : filteredTokens;\n\n const handleTokenClick = useTokenSelect(formType, onClick);\n const showCategories =\n Boolean(featuredTokens?.length || popularTokens?.length) &&\n !tokenSearchFilter;\n\n return (\n \n {!tokens.length && !isLoading ? (\n \n ) : null}\n \n \n );\n};\n","import type { TokenAmount } from '../../types/token.js';\n\nexport const filteredTokensComparator = (searchFilter: string) => {\n const isExactMatch = (token: TokenAmount) => {\n return (\n token.name?.toUpperCase() === searchFilter ||\n token.symbol.toUpperCase() === searchFilter ||\n token.address.toUpperCase() === searchFilter\n );\n };\n return (tokenA: TokenAmount, tokenB: TokenAmount) => {\n const isExactMatchA = isExactMatch(tokenA);\n const isExactMatchB = isExactMatch(tokenB);\n\n // Exact match with logo\n if (isExactMatchB && tokenB.logoURI) {\n return 1;\n }\n if (isExactMatchA && tokenA.logoURI) {\n return -1;\n }\n\n // Any token with a logo (exact match or not)\n if (tokenB.logoURI && !tokenA.logoURI) {\n return 1;\n }\n if (tokenA.logoURI && !tokenB.logoURI) {\n return -1;\n }\n\n // Exact match without logo\n if (isExactMatchB && !tokenB.logoURI) {\n return 1;\n }\n if (isExactMatchA && !tokenA.logoURI) {\n return -1;\n }\n\n // All other tokens are considered equal in sorting priority\n return 0;\n };\n};\n","import { useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { SearchInput } from '../../components/Search/SearchInput.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useFieldController } from '../../stores/form/useFieldController.js';\n\nexport const SearchTokenInput = () => {\n const { t } = useTranslation();\n const { setFieldValue } = useFieldActions();\n const { onChange, onBlur, name, value } = useFieldController({\n name: 'tokenSearchFilter',\n });\n\n useEffect(\n () => () => {\n setFieldValue('tokenSearchFilter', '');\n },\n [setFieldValue],\n );\n\n return (\n onChange((e.target as HTMLInputElement).value)}\n onBlur={onBlur}\n value={value as string | undefined}\n />\n );\n};\n","import { debounce, useTheme } from '@mui/material';\nimport type { MutableRefObject } from 'react';\nimport { useLayoutEffect, useState } from 'react';\nimport { useDefaultElementId } from '../../hooks/useDefaultElementId.js';\nimport {\n ElementId,\n getAppContainer,\n getHeaderElement,\n getScrollableContainer,\n} from '../../utils/elements.js';\n\nconst getContentHeight = (\n elementId: string,\n listParentRef: MutableRefObject,\n) => {\n const containerElement = getScrollableContainer(elementId);\n\n const headerElement = getHeaderElement(elementId);\n\n const listParentElement = listParentRef?.current;\n\n let oldHeight;\n\n // This covers the case where in full height flex mode when the browser height is reduced\n // - this allows the virtualised token list to be made smaller\n if (listParentElement) {\n oldHeight = listParentElement.style.height;\n listParentElement.style.height = '0';\n }\n\n if (!containerElement || !headerElement) {\n console.warn(\n `Can't find ${ElementId.ScrollableContainer} or ${ElementId.Header} id.`,\n );\n return 0;\n }\n const { height: containerHeight } = containerElement.getBoundingClientRect();\n const { height: headerHeight } = headerElement.getBoundingClientRect();\n\n // This covers the case where in full height flex mode when the browser height is reduced the\n // - this allows the virtualised token list to be set to minimum size\n if (listParentElement && oldHeight) {\n listParentElement.style.height = oldHeight;\n }\n\n return containerHeight - headerHeight;\n};\n\ninterface UseContentHeightProps {\n listParentRef: MutableRefObject;\n headerRef: MutableRefObject;\n}\n\nexport const minTokenListHeight = 360;\nexport const minMobileTokenListHeight = 160;\n\n// NOTE: this hook is implicitly tied to the widget height functionality in the\n// AppExpandedContainer, RelativeContainer and CssBaselineContainer components as defined in AppContainer.ts\n// CSS changes in those components can have implications for the functionality in this hook\n\nexport const useTokenListHeight = ({\n listParentRef,\n headerRef,\n}: UseContentHeightProps) => {\n const elementId = useDefaultElementId();\n const [contentHeight, setContentHeight] = useState(0);\n const theme = useTheme();\n\n useLayoutEffect(() => {\n const handleResize = () => {\n setContentHeight(getContentHeight(elementId, listParentRef));\n };\n\n const processResize = debounce(() => handleResize(), 40);\n\n // calling this on initial mount prevents the lists resizing appearing glitchy\n handleResize();\n\n const appContainer = getAppContainer(elementId);\n\n let resizeObserver: ResizeObserver;\n if (appContainer) {\n resizeObserver = new ResizeObserver(processResize);\n resizeObserver.observe(appContainer);\n }\n\n return () => {\n if (resizeObserver) {\n resizeObserver.disconnect();\n }\n };\n }, [elementId, listParentRef]);\n\n const minListHeight =\n theme.container?.height === '100%'\n ? minMobileTokenListHeight\n : minTokenListHeight;\n\n const tokenListHeight = Math.max(\n contentHeight - (headerRef.current?.offsetHeight ?? 0),\n minListHeight,\n );\n\n return {\n minListHeight,\n tokenListHeight,\n };\n};\n","import { Box } from '@mui/material';\nimport type { FC } from 'react';\nimport { useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { ChainSelect } from '../../components/ChainSelect/ChainSelect.js';\nimport { FullPageContainer } from '../../components/FullPageContainer.js';\nimport { TokenList } from '../../components/TokenList/TokenList.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useScrollableOverflowHidden } from '../../hooks/useScrollableContainer.js';\nimport { useSwapOnly } from '../../hooks/useSwapOnly.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { FormTypeProps } from '../../stores/form/types.js';\nimport { SearchTokenInput } from './SearchTokenInput.js';\nimport { useTokenListHeight } from './useTokenListHeight.js';\n\nexport const SelectTokenPage: FC = ({ formType }) => {\n useScrollableOverflowHidden();\n const { navigateBack } = useNavigateBack();\n const headerRef = useRef(null);\n const listParentRef = useRef(null);\n const { tokenListHeight, minListHeight } = useTokenListHeight({\n listParentRef,\n headerRef,\n });\n\n const swapOnly = useSwapOnly();\n\n const { subvariant } = useWidgetConfig();\n const { t } = useTranslation();\n const title =\n formType === 'from'\n ? subvariant === 'custom'\n ? t(`header.payWith`)\n : t(`header.from`)\n : t(`header.to`);\n\n useHeader(title);\n\n const hideChainSelect = swapOnly && formType === 'to';\n\n return (\n \n \n {!hideChainSelect ? : null}\n \n \n \n \n \n \n \n \n );\n};\n","export const version = '2.13.8'\n","import type { Compute, OneOf } from '../types/utils.js'\nimport { getVersion } from '../utils/getVersion.js'\n\nexport type ErrorType = Error & { name: name }\n\ntype BaseErrorOptions = Compute<\n OneOf<{ details?: string | undefined } | { cause: BaseError | Error }> & {\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n }\n>\n\nexport type BaseErrorType = BaseError & { name: 'WagmiCoreError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n\n override name = 'WagmiCoreError'\n get docsBaseUrl() {\n return 'https://wagmi.sh/core'\n }\n get version() {\n return getVersion()\n }\n\n constructor(shortMessage: string, options: BaseErrorOptions = {}) {\n super()\n\n const details =\n options.cause instanceof BaseError\n ? options.cause.details\n : options.cause?.message\n ? options.cause.message\n : options.details!\n const docsPath =\n options.cause instanceof BaseError\n ? options.cause.docsPath || options.docsPath\n : options.docsPath\n\n this.message = [\n shortMessage || 'An error occurred.',\n '',\n ...(options.metaMessages ? [...options.metaMessages, ''] : []),\n ...(docsPath\n ? [\n `Docs: ${this.docsBaseUrl}${docsPath}.html${\n options.docsSlug ? `#${options.docsSlug}` : ''\n }`,\n ]\n : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: ${this.version}`,\n ].join('\\n')\n\n if (options.cause) this.cause = options.cause\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = options.metaMessages\n this.shortMessage = shortMessage\n }\n\n walk(fn?: (err: unknown) => boolean) {\n return this.#walk(this, fn)\n }\n\n #walk(err: unknown, fn?: (err: unknown) => boolean): unknown {\n if (fn?.(err)) return err\n if ((err as Error).cause) return this.#walk((err as Error).cause, fn)\n return err\n }\n}\n","import { version } from '../version.js'\n\nexport const getVersion = () => `@wagmi/core@${version}`\n","import type { Connector } from '../createConfig.js'\nimport { BaseError } from './base.js'\n\nexport type ProviderNotFoundErrorType = ProviderNotFoundError & {\n name: 'ProviderNotFoundError'\n}\nexport class ProviderNotFoundError extends BaseError {\n override name = 'ProviderNotFoundError'\n constructor() {\n super('Provider not found.')\n }\n}\n\nexport type SwitchChainNotSupportedErrorType = SwitchChainNotSupportedError & {\n name: 'SwitchChainNotSupportedError'\n}\nexport class SwitchChainNotSupportedError extends BaseError {\n override name = 'SwitchChainNotSupportedError'\n\n constructor({ connector }: { connector: Connector }) {\n super(`\"${connector.name}\" does not support programmatic chain switching.`)\n }\n}\n","import type { Chain, Transport } from 'viem'\n\ntype ExtractRpcUrlsParameters = {\n transports?: Record | undefined\n chain: Chain\n}\n\nexport function extractRpcUrls(parameters: ExtractRpcUrlsParameters) {\n const { chain } = parameters\n const fallbackUrl = chain.rpcUrls.default.http[0]\n\n if (!parameters.transports) return [fallbackUrl]\n\n const transport = parameters.transports?.[chain.id]?.({ chain })\n const transports = (transport?.value?.transports as NonNullable<\n typeof transport\n >[]) || [transport]\n return transports.map(({ value }) => value?.url || fallbackUrl)\n}\n","import type { Address } from 'viem'\n\nimport type { Connector } from '../createConfig.js'\nimport { BaseError } from './base.js'\n\nexport type ChainNotConfiguredErrorType = ChainNotConfiguredError & {\n name: 'ChainNotConfiguredError'\n}\nexport class ChainNotConfiguredError extends BaseError {\n override name = 'ChainNotConfiguredError'\n constructor() {\n super('Chain not configured.')\n }\n}\n\nexport type ConnectorAlreadyConnectedErrorType =\n ConnectorAlreadyConnectedError & {\n name: 'ConnectorAlreadyConnectedError'\n }\nexport class ConnectorAlreadyConnectedError extends BaseError {\n override name = 'ConnectorAlreadyConnectedError'\n constructor() {\n super('Connector already connected.')\n }\n}\n\nexport type ConnectorNotConnectedErrorType = ConnectorNotConnectedError & {\n name: 'ConnectorNotConnectedError'\n}\nexport class ConnectorNotConnectedError extends BaseError {\n override name = 'ConnectorNotConnectedError'\n constructor() {\n super('Connector not connected.')\n }\n}\n\nexport type ConnectorNotFoundErrorType = ConnectorNotFoundError & {\n name: 'ConnectorNotFoundError'\n}\nexport class ConnectorNotFoundError extends BaseError {\n override name = 'ConnectorNotFoundError'\n constructor() {\n super('Connector not found.')\n }\n}\n\nexport type ConnectorAccountNotFoundErrorType =\n ConnectorAccountNotFoundError & {\n name: 'ConnectorAccountNotFoundError'\n }\nexport class ConnectorAccountNotFoundError extends BaseError {\n override name = 'ConnectorAccountNotFoundError'\n constructor({\n address,\n connector,\n }: {\n address: Address\n connector: Connector\n }) {\n super(`Account \"${address}\" not found for connector \"${connector.name}\".`)\n }\n}\n\nexport type ConnectorChainMismatchErrorType = ConnectorAccountNotFoundError & {\n name: 'ConnectorChainMismatchError'\n}\nexport class ConnectorChainMismatchError extends BaseError {\n override name = 'ConnectorChainMismatchError'\n constructor({\n connectionChainId,\n connectorChainId,\n }: {\n connectionChainId: number\n connectorChainId: number\n }) {\n super(\n `The current chain of the connector (id: ${connectorChainId}) does not match the connection's chain (id: ${connectionChainId}).`,\n {\n metaMessages: [\n `Current Chain ID: ${connectorChainId}`,\n `Expected Chain ID: ${connectionChainId}`,\n ],\n },\n )\n }\n}\n\nexport type ConnectorUnavailableReconnectingErrorType =\n ConnectorUnavailableReconnectingError & {\n name: 'ConnectorUnavailableReconnectingError'\n }\nexport class ConnectorUnavailableReconnectingError extends BaseError {\n override name = 'ConnectorUnavailableReconnectingError'\n constructor({ connector }: { connector: { name: string } }) {\n super(`Connector \"${connector.name}\" unavailable while reconnecting.`, {\n details: [\n 'During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uuid`.',\n 'All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored.',\n 'This error commonly occurs for connectors that asynchronously inject after reconnection has already started.',\n ].join(' '),\n })\n }\n}\n","export const version = '2.21.17'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = '',\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n docsSlug ? `#${docsSlug}` : ''\n }`\n : undefined,\n version,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n errorConfig = config\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined\n details?: string | undefined\n docsBaseUrl?: string | undefined\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n version: string\n\n override name = 'BaseError'\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details\n if (args.cause?.message) return args.cause.message\n return args.details!\n })()\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath\n return args.docsPath\n })()\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n')\n\n super(message, args.cause ? { cause: args.cause } : undefined)\n\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.name = args.name ?? this.name\n this.shortMessage = shortMessage\n this.version = version\n }\n\n walk(): Error\n walk(fn: (err: unknown) => boolean): Error | null\n walk(fn?: any): any {\n return walk(this, fn)\n }\n}\n\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (err && typeof err === 'object' && 'cause' in err)\n return walk(err.cause, fn)\n return fn ? null : err\n}\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n })\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type IsHexErrorType = ErrorType\n\nexport function isHex(\n value: unknown,\n { strict = true }: { strict?: boolean | undefined } = {},\n): value is Hex {\n if (!value) return false\n if (typeof value !== 'string') return false\n return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x')\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n constructor({\n offset,\n position,\n size,\n }: { offset: number; position: 'start' | 'end'; size: number }) {\n super(\n `Slice ${\n position === 'start' ? 'starting' : 'ending'\n } at offset \"${offset}\" is out-of-bounds (size: ${size}).`,\n { name: 'SliceOffsetOutOfBoundsError' },\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'hex' | 'bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`,\n { name: 'SizeExceedsPaddingSizeError' },\n )\n }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\n constructor({\n size,\n targetSize,\n type,\n }: {\n size: number\n targetSize: number\n type: 'hex' | 'bytes'\n }) {\n super(\n `${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n { name: 'InvalidBytesLengthError' },\n )\n }\n}\n","import {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype PadOptions = {\n dir?: 'left' | 'right' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType = value extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad(\n hexOrBytes: value,\n { dir, size = 32 }: PadOptions = {},\n): PadReturnType {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size }) as PadReturnType\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType\n}\n\nexport type PadHexErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padHex(hex_: Hex, { dir, size = 32 }: PadOptions = {}) {\n if (size === null) return hex_\n const hex = hex_.replace('0x', '')\n if (hex.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'hex',\n })\n\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](\n size * 2,\n '0',\n )}` as Hex\n}\n\nexport type PadBytesErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padBytes(\n bytes: ByteArray,\n { dir, size = 32 }: PadOptions = {},\n) {\n if (size === null) return bytes\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n })\n const paddedBytes = new Uint8Array(size)\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right'\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1]\n }\n return paddedBytes\n}\n","import type { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\n value: string\n }) {\n super(\n `Number \"${value}\" is not in safe ${\n size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''\n }integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`,\n { name: 'IntegerOutOfRangeError' },\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\n constructor(bytes: ByteArray) {\n super(\n `Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,\n {\n name: 'InvalidBytesBooleanError',\n },\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\n constructor(hex: Hex) {\n super(\n `Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`,\n { name: 'InvalidHexBooleanError' },\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n { name: 'InvalidHexValueError' },\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n { name: 'SizeOverflowError' },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\n\nexport type SizeErrorType = IsHexErrorType | ErrorType\n\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value: Hex | ByteArray) {\n if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2)\n return value.length\n}\n","import {\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type SizeErrorType, size as size_ } from '../data/size.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\n\nexport type AssertSizeErrorType =\n | SizeOverflowErrorType\n | SizeErrorType\n | ErrorType\n\nexport function assertSize(\n hexOrBytes: Hex | ByteArray,\n { size }: { size: number },\n): void {\n if (size_(hexOrBytes) > size)\n throw new SizeOverflowError({\n givenSize: size_(hexOrBytes),\n maxSize: size,\n })\n}\n\nexport type FromHexParameters<\n to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | to\n | {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromHexReturnType = to extends 'string'\n ? string\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'bytes'\n ? ByteArray\n : to extends 'boolean'\n ? boolean\n : never\n\nexport type FromHexErrorType =\n | HexToNumberErrorType\n | HexToBigIntErrorType\n | HexToBoolErrorType\n | HexToStringErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex\n * - Example: https://viem.sh/docs/utilities/fromHex#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex<\n to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n>(hex: Hex, toOrOpts: FromHexParameters): FromHexReturnType {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number') return hexToNumber(hex, opts) as FromHexReturnType\n if (to === 'bigint') return hexToBigInt(hex, opts) as FromHexReturnType\n if (to === 'string') return hexToString(hex, opts) as FromHexReturnType\n if (to === 'boolean') return hexToBool(hex, opts) as FromHexReturnType\n return hexToBytes(hex, opts) as FromHexReturnType\n}\n\nexport type HexToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n}\n\nexport type HexToBigIntErrorType = AssertSizeErrorType | ErrorType\n\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex: Hex, opts: HexToBigIntOpts = {}): bigint {\n const { signed } = opts\n\n if (opts.size) assertSize(hex, { size: opts.size })\n\n const value = BigInt(hex)\n if (!signed) return value\n\n const size = (hex.length - 2) / 2\n const max = (1n << (BigInt(size) * 8n - 1n)) - 1n\n if (value <= max) return value\n\n return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n\n}\n\nexport type HexToBoolOpts = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n}\n\nexport type HexToBoolErrorType =\n | AssertSizeErrorType\n | InvalidHexBooleanErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_: Hex, opts: HexToBoolOpts = {}): boolean {\n let hex = hex_\n if (opts.size) {\n assertSize(hex, { size: opts.size })\n hex = trim(hex)\n }\n if (trim(hex) === '0x00') return false\n if (trim(hex) === '0x01') return true\n throw new InvalidHexBooleanError(hex)\n}\n\nexport type HexToNumberOpts = HexToBigIntOpts\n\nexport type HexToNumberErrorType = HexToBigIntErrorType | ErrorType\n\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex: Hex, opts: HexToNumberOpts = {}): number {\n return Number(hexToBigInt(hex, opts))\n}\n\nexport type HexToStringOpts = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n}\n\nexport type HexToStringErrorType =\n | AssertSizeErrorType\n | HexToBytesErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex: Hex, opts: HexToStringOpts = {}): string {\n let bytes = hexToBytes(hex)\n if (opts.size) {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n i.toString(16).padStart(2, '0'),\n)\n\nexport type ToHexParameters = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n}\n\nexport type ToHexErrorType =\n | BoolToHexErrorType\n | BytesToHexErrorType\n | NumberToHexErrorType\n | StringToHexErrorType\n | ErrorType\n\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex\n * - Example: https://viem.sh/docs/utilities/toHex#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(\n value: string | number | bigint | boolean | ByteArray,\n opts: ToHexParameters = {},\n): Hex {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToHex(value, opts)\n if (typeof value === 'string') {\n return stringToHex(value, opts)\n }\n if (typeof value === 'boolean') return boolToHex(value, opts)\n return bytesToHex(value, opts)\n}\n\nexport type BoolToHexOpts = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n}\n\nexport type BoolToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value: boolean, opts: BoolToHexOpts = {}): Hex {\n const hex: Hex = `0x${Number(value)}`\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size })\n return pad(hex, { size: opts.size })\n }\n return hex\n}\n\nexport type BytesToHexOpts = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n}\n\nexport type BytesToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value: ByteArray, opts: BytesToHexOpts = {}): Hex {\n let string = ''\n for (let i = 0; i < value.length; i++) {\n string += hexes[value[i]]\n }\n const hex = `0x${string}` as const\n\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size })\n return pad(hex, { dir: 'right', size: opts.size })\n }\n return hex\n}\n\nexport type NumberToHexOpts =\n | {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n }\n\nexport type NumberToHexErrorType =\n | IntegerOutOfRangeErrorType\n | PadErrorType\n | ErrorType\n\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(\n value_: number | bigint,\n opts: NumberToHexOpts = {},\n): Hex {\n const { signed, size } = opts\n\n const value = BigInt(value_)\n\n let maxValue: bigint | number | undefined\n if (size) {\n if (signed) maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n\n else maxValue = 2n ** (BigInt(size) * 8n) - 1n\n } else if (typeof value_ === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER)\n }\n\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0\n\n if ((maxValue && value > maxValue) || value < minValue) {\n const suffix = typeof value_ === 'bigint' ? 'n' : ''\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value_}${suffix}`,\n })\n }\n\n const hex = `0x${(signed && value < 0\n ? (1n << BigInt(size * 8)) + BigInt(value)\n : value\n ).toString(16)}` as Hex\n if (size) return pad(hex, { size }) as Hex\n return hex\n}\n\nexport type StringToHexOpts = {\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\n}\n\nexport type StringToHexErrorType = BytesToHexErrorType | ErrorType\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_: string, opts: StringToHexOpts = {}): Hex {\n const value = encoder.encode(value_)\n return bytesToHex(value, opts)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\nimport {\n type NumberToHexErrorType,\n type NumberToHexOpts,\n numberToHex,\n} from './toHex.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nexport type ToBytesParameters = {\n /** Size of the output bytes. */\n size?: number | undefined\n}\n\nexport type ToBytesErrorType =\n | NumberToBytesErrorType\n | BoolToBytesErrorType\n | HexToBytesErrorType\n | StringToBytesErrorType\n | IsHexErrorType\n | ErrorType\n\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes\n * - Example: https://viem.sh/docs/utilities/toBytes#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(\n value: string | bigint | number | boolean | Hex,\n opts: ToBytesParameters = {},\n): ByteArray {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToBytes(value, opts)\n if (typeof value === 'boolean') return boolToBytes(value, opts)\n if (isHex(value)) return hexToBytes(value, opts)\n return stringToBytes(value, opts)\n}\n\nexport type BoolToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\n}\n\nexport type BoolToBytesErrorType =\n | AssertSizeErrorType\n | PadErrorType\n | ErrorType\n\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value: boolean, opts: BoolToBytesOpts = {}) {\n const bytes = new Uint8Array(1)\n bytes[0] = Number(value)\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size })\n return pad(bytes, { size: opts.size })\n }\n return bytes\n}\n\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n} as const\n\nfunction charCodeToBase16(char: number) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10)\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10)\n return undefined\n}\n\nexport type HexToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\n}\n\nexport type HexToBytesErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_: Hex, opts: HexToBytesOpts = {}): ByteArray {\n let hex = hex_\n if (opts.size) {\n assertSize(hex, { size: opts.size })\n hex = pad(hex, { dir: 'right', size: opts.size })\n }\n\n let hexString = hex.slice(2) as string\n if (hexString.length % 2) hexString = `0${hexString}`\n\n const length = hexString.length / 2\n const bytes = new Uint8Array(length)\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++))\n const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++))\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new BaseError(\n `Invalid byte sequence (\"${hexString[j - 2]}${\n hexString[j - 1]\n }\" in \"${hexString}\").`,\n )\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight\n }\n return bytes\n}\n\nexport type NumberToBytesErrorType =\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(\n value: bigint | number,\n opts?: NumberToHexOpts | undefined,\n) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\n}\n\nexport type StringToBytesErrorType =\n | AssertSizeErrorType\n | PadErrorType\n | ErrorType\n\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(\n value: string,\n opts: StringToBytesOpts = {},\n): ByteArray {\n const bytes = encoder.encode(value)\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size })\n return pad(bytes, { dir: 'right', size: opts.size })\n }\n return bytes\n}\n","import { keccak_256 } from '@noble/hashes/sha3'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Keccak256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Keccak256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function keccak256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Keccak256Hash {\n const to = to_ || 'hex'\n const bytes = keccak_256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Keccak256Hash\n return toHex(bytes) as Keccak256Hash\n}\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\n}\n","import type { Address } from 'abitype'\n\nimport { InvalidAddressError } from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap
(8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase()\n const hash = keccak256(stringToBytes(hexAddress), 'bytes')\n\n const address = (\n chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress\n ).split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase()\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase()\n }\n }\n\n const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import type { ErrorType } from '../errors/utils.js'\n\nexport type StringifyErrorType = ErrorType\n\nexport const stringify: typeof JSON.stringify = (value, replacer, space) =>\n JSON.stringify(\n value,\n (key, value_) => {\n const value = typeof value_ === 'bigint' ? value_.toString() : value_\n return typeof replacer === 'function' ? replacer(key, value) : value\n },\n space,\n )\n","import { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type HttpRequestErrorType = HttpRequestError & {\n name: 'HttpRequestError'\n}\nexport class HttpRequestError extends BaseError {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n\n constructor({\n body,\n cause,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n cause?: Error | undefined\n details?: string | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'HttpRequestError',\n })\n this.body = body\n this.headers = headers\n this.status = status\n this.url = url\n }\n}\n\nexport type WebSocketRequestErrorType = WebSocketRequestError & {\n name: 'WebSocketRequestError'\n}\nexport class WebSocketRequestError extends BaseError {\n constructor({\n body,\n cause,\n details,\n url,\n }: {\n body?: { [key: string]: unknown } | undefined\n cause?: Error | undefined\n details?: string | undefined\n url: string\n }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'WebSocketRequestError',\n })\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; message: string }\n url: string\n }) {\n super('RPC Request failed.', {\n cause: error as any,\n details: error.message,\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n name: 'RpcRequestError',\n })\n this.code = error.code\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n constructor({\n url,\n }: {\n url?: string | undefined\n } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean) as string[],\n name: 'SocketClosedError',\n })\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n constructor({\n body,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n url: string\n }) {\n super('The request took too long to respond.', {\n details: 'The request timed out.',\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n name: 'TimeoutError',\n })\n }\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n | -1\n | -32700 // Parse error\n | -32600 // Invalid request\n | -32601 // Method not found\n | -32602 // Invalid params\n | -32603 // Internal error\n | -32000 // Invalid input\n | -32001 // Resource not found\n | -32002 // Resource unavailable\n | -32003 // Transaction rejected\n | -32004 // Method not supported\n | -32005 // Limit exceeded\n | -32006 // JSON-RPC version not supported\n | -32042 // Method not found\n\ntype RpcErrorOptions = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode\n ) as code_\n }\n}\n\nexport type ProviderRpcErrorCode =\n | 4001 // User Rejected Request\n | 4100 // Unauthorized\n | 4200 // Unsupported Method\n | 4900 // Disconnected\n | 4901 // Chain Disconnected\n | 4902 // Chain Not Recognized\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n T = undefined,\n> extends RpcError {\n data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions & {\n data?: T | undefined\n }\n >,\n ) {\n super(cause, options)\n\n this.data = options.data\n }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n code: -32700\n name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage:\n 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n })\n }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n code: -32600\n name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n code: -32601\n name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n code: -32602\n name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n code: -32603\n name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n code: -32000\n name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n code: -32001\n name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n override name = 'ResourceNotFoundRpcError'\n static code = -32001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n })\n }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n code: -32002\n name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n })\n }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n code: -32003\n name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n code: -32004\n name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not implemented.`,\n })\n }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n code: -32005\n name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n })\n }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n JsonRpcVersionUnsupportedError & {\n code: -32006\n name: 'JsonRpcVersionUnsupportedError'\n }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n })\n }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n code: 4001\n name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n code: 4100\n name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage:\n 'The requested method and/or account has not been authorized by the user.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n UnsupportedProviderMethodError & {\n code: 4200\n name: 'UnsupportedProviderMethodError'\n }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n code: 4900\n name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n })\n }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n code: 4901\n name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n code: 4902\n name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\n}\n","import {\n ChainNotConfiguredError,\n type Connector,\n ProviderNotFoundError,\n createConnector,\n extractRpcUrls,\n} from '@wagmi/core'\nimport type { Compute, ExactPartial, Omit } from '@wagmi/core/internal'\nimport type { EthereumProvider } from '@walletconnect/ethereum-provider'\nimport {\n type AddEthereumChainParameter,\n type Address,\n type ProviderConnectInfo,\n type ProviderRpcError,\n type RpcError,\n SwitchChainError,\n UserRejectedRequestError,\n getAddress,\n numberToHex,\n} from 'viem'\n\ntype WalletConnectConnector = Connector & {\n onDisplayUri(uri: string): void\n onSessionDelete(data: { topic: string }): void\n}\n\ntype EthereumProviderOptions = Parameters<(typeof EthereumProvider)['init']>[0]\n\nexport type WalletConnectParameters = Compute<\n {\n /**\n * If a new chain is added to a previously existing configured connector `chains`, this flag\n * will determine if that chain should be considered as stale. A stale chain is a chain that\n * WalletConnect has yet to establish a relationship with (e.g. the user has not approved or\n * rejected the chain).\n *\n * This flag mainly affects the behavior when a wallet does not support dynamic chain authorization\n * with WalletConnect v2.\n *\n * If `true` (default), the new chain will be treated as a stale chain. If the user\n * has yet to establish a relationship (approved/rejected) with this chain in their WalletConnect\n * session, the connector will disconnect upon the dapp auto-connecting, and the user will have to\n * reconnect to the dapp (revalidate the chain) in order to approve the newly added chain.\n * This is the default behavior to avoid an unexpected error upon switching chains which may\n * be a confusing user experience (e.g. the user will not know they have to reconnect\n * unless the dapp handles these types of errors).\n *\n * If `false`, the new chain will be treated as a potentially valid chain. This means that if the user\n * has yet to establish a relationship with the chain in their WalletConnect session, wagmi will successfully\n * auto-connect the user. This comes with the trade-off that the connector will throw an error\n * when attempting to switch to the unapproved chain if the wallet does not support dynamic session updates.\n * This may be useful in cases where a dapp constantly\n * modifies their configured chains, and they do not want to disconnect the user upon\n * auto-connecting. If the user decides to switch to the unapproved chain, it is important that the\n * dapp handles this error and prompts the user to reconnect to the dapp in order to approve\n * the newly added chain.\n *\n * @default true\n */\n isNewChainsStale?: boolean\n } & Omit<\n EthereumProviderOptions,\n | 'chains'\n | 'events'\n | 'optionalChains'\n | 'optionalEvents'\n | 'optionalMethods'\n | 'methods'\n | 'rpcMap'\n | 'showQrModal'\n > &\n ExactPartial>\n>\n\nwalletConnect.type = 'walletConnect' as const\nexport function walletConnect(parameters: WalletConnectParameters) {\n const isNewChainsStale = parameters.isNewChainsStale ?? true\n\n type Provider = Awaited>\n type Properties = {\n connect(parameters?: { chainId?: number; pairingTopic?: string }): Promise<{\n accounts: readonly Address[]\n chainId: number\n }>\n getNamespaceChainsIds(): number[]\n getRequestedChainsIds(): Promise\n isChainsStale(): Promise\n onConnect(connectInfo: ProviderConnectInfo): void\n onDisplayUri(uri: string): void\n onSessionDelete(data: { topic: string }): void\n setRequestedChainsIds(chains: number[]): void\n requestedChainsStorageKey: `${string}.requestedChains`\n }\n type StorageItem = {\n [_ in Properties['requestedChainsStorageKey']]: number[]\n }\n\n let provider_: Provider | undefined\n let providerPromise: Promise\n const NAMESPACE = 'eip155'\n\n let accountsChanged: WalletConnectConnector['onAccountsChanged'] | undefined\n let chainChanged: WalletConnectConnector['onChainChanged'] | undefined\n let connect: WalletConnectConnector['onConnect'] | undefined\n let displayUri: WalletConnectConnector['onDisplayUri'] | undefined\n let sessionDelete: WalletConnectConnector['onSessionDelete'] | undefined\n let disconnect: WalletConnectConnector['onDisconnect'] | undefined\n\n return createConnector((config) => ({\n id: 'walletConnect',\n name: 'WalletConnect',\n type: walletConnect.type,\n async setup() {\n const provider = await this.getProvider().catch(() => null)\n if (!provider) return\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect)\n }\n if (!sessionDelete) {\n sessionDelete = this.onSessionDelete.bind(this)\n provider.on('session_delete', sessionDelete)\n }\n },\n async connect({ chainId, ...rest } = {}) {\n try {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n if (!displayUri) {\n displayUri = this.onDisplayUri\n provider.on('display_uri', displayUri)\n }\n\n let targetChainId = chainId\n if (!targetChainId) {\n const state = (await config.storage?.getItem('state')) ?? {}\n const isChainSupported = config.chains.some(\n (x) => x.id === state.chainId,\n )\n if (isChainSupported) targetChainId = state.chainId\n else targetChainId = config.chains[0]?.id\n }\n if (!targetChainId) throw new Error('No chains found on connector.')\n\n const isChainsStale = await this.isChainsStale()\n // If there is an active session with stale chains, disconnect current session.\n if (provider.session && isChainsStale) await provider.disconnect()\n\n // If there isn't an active session or chains are stale, connect.\n if (!provider.session || isChainsStale) {\n const optionalChains = config.chains\n .filter((chain) => chain.id !== targetChainId)\n .map((optionalChain) => optionalChain.id)\n await provider.connect({\n optionalChains: [targetChainId, ...optionalChains],\n ...('pairingTopic' in rest\n ? { pairingTopic: rest.pairingTopic }\n : {}),\n })\n\n this.setRequestedChainsIds(config.chains.map((x) => x.id))\n }\n\n // If session exists and chains are authorized, enable provider for required chain\n const accounts = (await provider.enable()).map((x) => getAddress(x))\n const currentChainId = await this.getChainId()\n\n if (displayUri) {\n provider.removeListener('display_uri', displayUri)\n displayUri = undefined\n }\n if (connect) {\n provider.removeListener('connect', connect)\n connect = undefined\n }\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect)\n }\n if (!sessionDelete) {\n sessionDelete = this.onSessionDelete.bind(this)\n provider.on('session_delete', sessionDelete)\n }\n\n return { accounts, chainId: currentChainId }\n } catch (error) {\n if (\n /(user rejected|connection request reset)/i.test(\n (error as ProviderRpcError)?.message,\n )\n ) {\n throw new UserRejectedRequestError(error as Error)\n }\n throw error\n }\n },\n async disconnect() {\n const provider = await this.getProvider()\n try {\n await provider?.disconnect()\n } catch (error) {\n if (!/No matching key/i.test((error as Error).message)) throw error\n } finally {\n if (chainChanged) {\n provider?.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider?.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider?.on('connect', connect)\n }\n if (accountsChanged) {\n provider?.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (sessionDelete) {\n provider?.removeListener('session_delete', sessionDelete)\n sessionDelete = undefined\n }\n\n this.setRequestedChainsIds([])\n }\n },\n async getAccounts() {\n const provider = await this.getProvider()\n return provider.accounts.map((x) => getAddress(x))\n },\n async getProvider({ chainId } = {}) {\n async function initProvider() {\n const optionalChains = config.chains.map((x) => x.id) as [number]\n if (!optionalChains.length) return\n const { EthereumProvider } = await import(\n '@walletconnect/ethereum-provider'\n )\n return await EthereumProvider.init({\n ...parameters,\n disableProviderPing: true,\n optionalChains,\n projectId: parameters.projectId,\n rpcMap: Object.fromEntries(\n config.chains.map((chain) => {\n const [url] = extractRpcUrls({\n chain,\n transports: config.transports,\n })\n return [chain.id, url]\n }),\n ),\n showQrModal: parameters.showQrModal ?? true,\n })\n }\n\n if (!provider_) {\n if (!providerPromise) providerPromise = initProvider()\n provider_ = await providerPromise\n provider_?.events.setMaxListeners(Number.POSITIVE_INFINITY)\n }\n if (chainId) await this.switchChain?.({ chainId })\n return provider_!\n },\n async getChainId() {\n const provider = await this.getProvider()\n return provider.chainId\n },\n async isAuthorized() {\n try {\n const [accounts, provider] = await Promise.all([\n this.getAccounts(),\n this.getProvider(),\n ])\n\n // If an account does not exist on the session, then the connector is unauthorized.\n if (!accounts.length) return false\n\n // If the chains are stale on the session, then the connector is unauthorized.\n const isChainsStale = await this.isChainsStale()\n if (isChainsStale && provider.session) {\n await provider.disconnect().catch(() => {})\n return false\n }\n return true\n } catch {\n return false\n }\n },\n async switchChain({ addEthereumChainParameter, chainId }) {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n\n const chain = config.chains.find((x) => x.id === chainId)\n if (!chain) throw new SwitchChainError(new ChainNotConfiguredError())\n\n try {\n await Promise.all([\n new Promise((resolve) => {\n const listener = ({\n chainId: currentChainId,\n }: { chainId?: number | undefined }) => {\n if (currentChainId === chainId) {\n config.emitter.off('change', listener)\n resolve()\n }\n }\n config.emitter.on('change', listener)\n }),\n provider.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: numberToHex(chainId) }],\n }),\n ])\n\n const requestedChains = await this.getRequestedChainsIds()\n this.setRequestedChainsIds([...requestedChains, chainId])\n\n return chain\n } catch (err) {\n const error = err as RpcError\n\n if (/(user rejected)/i.test(error.message))\n throw new UserRejectedRequestError(error)\n\n // Indicates chain is not added to provider\n try {\n let blockExplorerUrls: string[] | undefined\n if (addEthereumChainParameter?.blockExplorerUrls)\n blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls\n else\n blockExplorerUrls = chain.blockExplorers?.default.url\n ? [chain.blockExplorers?.default.url]\n : []\n\n let rpcUrls: readonly string[]\n if (addEthereumChainParameter?.rpcUrls?.length)\n rpcUrls = addEthereumChainParameter.rpcUrls\n else rpcUrls = [...chain.rpcUrls.default.http]\n\n const addEthereumChain = {\n blockExplorerUrls,\n chainId: numberToHex(chainId),\n chainName: addEthereumChainParameter?.chainName ?? chain.name,\n iconUrls: addEthereumChainParameter?.iconUrls,\n nativeCurrency:\n addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency,\n rpcUrls,\n } satisfies AddEthereumChainParameter\n\n await provider.request({\n method: 'wallet_addEthereumChain',\n params: [addEthereumChain],\n })\n\n const requestedChains = await this.getRequestedChainsIds()\n this.setRequestedChainsIds([...requestedChains, chainId])\n return chain\n } catch (error) {\n throw new UserRejectedRequestError(error as Error)\n }\n }\n },\n onAccountsChanged(accounts) {\n if (accounts.length === 0) this.onDisconnect()\n else\n config.emitter.emit('change', {\n accounts: accounts.map((x) => getAddress(x)),\n })\n },\n onChainChanged(chain) {\n const chainId = Number(chain)\n config.emitter.emit('change', { chainId })\n },\n async onConnect(connectInfo) {\n const chainId = Number(connectInfo.chainId)\n const accounts = await this.getAccounts()\n config.emitter.emit('connect', { accounts, chainId })\n },\n async onDisconnect(_error) {\n this.setRequestedChainsIds([])\n config.emitter.emit('disconnect')\n\n const provider = await this.getProvider()\n if (accountsChanged) {\n provider.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n if (sessionDelete) {\n provider.removeListener('session_delete', sessionDelete)\n sessionDelete = undefined\n }\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect)\n }\n },\n onDisplayUri(uri) {\n config.emitter.emit('message', { type: 'display_uri', data: uri })\n },\n onSessionDelete() {\n this.onDisconnect()\n },\n getNamespaceChainsIds() {\n if (!provider_) return []\n const chainIds = provider_.session?.namespaces[NAMESPACE]?.accounts?.map(\n (account) => Number.parseInt(account.split(':')[1] || ''),\n )\n return chainIds ?? []\n },\n async getRequestedChainsIds() {\n return (\n (await config.storage?.getItem(this.requestedChainsStorageKey)) ?? []\n )\n },\n /**\n * Checks if the target chains match the chains that were\n * initially requested by the connector for the WalletConnect session.\n * If there is a mismatch, this means that the chains on the connector\n * are considered stale, and need to be revalidated at a later point (via\n * connection).\n *\n * There may be a scenario where a dapp adds a chain to the\n * connector later on, however, this chain will not have been approved or rejected\n * by the wallet. In this case, the chain is considered stale.\n */\n async isChainsStale() {\n if (!isNewChainsStale) return false\n\n const connectorChains = config.chains.map((x) => x.id)\n const namespaceChains = this.getNamespaceChainsIds()\n if (\n namespaceChains.length &&\n !namespaceChains.some((id) => connectorChains.includes(id))\n )\n return false\n\n const requestedChains = await this.getRequestedChainsIds()\n return !connectorChains.every((id) => requestedChains.includes(id))\n },\n async setRequestedChainsIds(chains) {\n await config.storage?.setItem(this.requestedChainsStorageKey, chains)\n },\n get requestedChainsStorageKey() {\n return `${this.id}.requestedChains` as Properties['requestedChainsStorageKey']\n },\n }))\n}\n",null,null,null,"import type {\n CoinbaseWalletSDK,\n Preference,\n ProviderInterface,\n} from '@coinbase/wallet-sdk'\nimport {\n ChainNotConfiguredError,\n type Connector,\n createConnector,\n} from '@wagmi/core'\nimport type { Compute, Mutable, Omit } from '@wagmi/core/internal'\nimport type {\n CoinbaseWalletProvider as CBW_Provider,\n CoinbaseWalletSDK as CBW_SDK,\n} from 'cbw-sdk'\nimport {\n type AddEthereumChainParameter,\n type Hex,\n type ProviderRpcError,\n SwitchChainError,\n UserRejectedRequestError,\n getAddress,\n numberToHex,\n} from 'viem'\n\ntype Version = '3' | '4'\n\nexport type CoinbaseWalletParameters =\n version extends '4'\n ? Compute<\n {\n headlessMode?: false | undefined\n /** Coinbase Wallet SDK version */\n version?: version | '3' | undefined\n } & Version4Parameters\n >\n : Compute<\n {\n /**\n * @deprecated `headlessMode` will be removed in the next major version. Upgrade to `version: '4'`.\n */\n headlessMode?: true | undefined\n /**\n * Coinbase Wallet SDK version\n * @deprecated Version 3 will be removed in the next major version. Upgrade to `version: '4'`.\n * @default '4'\n */\n version?: version | '4' | undefined\n } & Version3Parameters\n >\n\ncoinbaseWallet.type = 'coinbaseWallet' as const\nexport function coinbaseWallet(\n parameters: CoinbaseWalletParameters = {} as any,\n): version extends '4'\n ? ReturnType\n : ReturnType {\n if (parameters.version === '3' || parameters.headlessMode)\n return version3(parameters as Version3Parameters) as any\n return version4(parameters as Version4Parameters) as any\n}\n\ntype Version4Parameters = Mutable<\n Omit<\n ConstructorParameters[0],\n 'appChainIds' // set via wagmi config\n > & {\n /**\n * Preference for the type of wallet to display.\n * @default 'all'\n */\n preference?: Preference['options'] | undefined\n }\n>\n\nfunction version4(parameters: Version4Parameters) {\n type Provider = ProviderInterface & {\n // for backwards compatibility\n close?(): void\n }\n\n let sdk: CoinbaseWalletSDK | undefined\n let walletProvider: Provider | undefined\n\n let accountsChanged: Connector['onAccountsChanged'] | undefined\n let chainChanged: Connector['onChainChanged'] | undefined\n let disconnect: Connector['onDisconnect'] | undefined\n\n return createConnector((config) => ({\n id: 'coinbaseWalletSDK',\n name: 'Coinbase Wallet',\n supportsSimulation: true,\n type: coinbaseWallet.type,\n async connect({ chainId } = {}) {\n try {\n const provider = await this.getProvider()\n const accounts = (\n (await provider.request({\n method: 'eth_requestAccounts',\n })) as string[]\n ).map((x) => getAddress(x))\n\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect)\n }\n\n // Switch to chain if provided\n let currentChainId = await this.getChainId()\n if (chainId && currentChainId !== chainId) {\n const chain = await this.switchChain!({ chainId }).catch((error) => {\n if (error.code === UserRejectedRequestError.code) throw error\n return { id: currentChainId }\n })\n currentChainId = chain?.id ?? currentChainId\n }\n\n return { accounts, chainId: currentChainId }\n } catch (error) {\n if (\n /(user closed modal|accounts received is empty|user denied account|request rejected)/i.test(\n (error as Error).message,\n )\n )\n throw new UserRejectedRequestError(error as Error)\n throw error\n }\n },\n async disconnect() {\n const provider = await this.getProvider()\n\n if (accountsChanged) {\n provider.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n\n provider.disconnect()\n provider.close?.()\n },\n async getAccounts() {\n const provider = await this.getProvider()\n return (\n await provider.request({\n method: 'eth_accounts',\n })\n ).map((x) => getAddress(x))\n },\n async getChainId() {\n const provider = await this.getProvider()\n const chainId = await provider.request({\n method: 'eth_chainId',\n })\n return Number(chainId)\n },\n async getProvider() {\n if (!walletProvider) {\n // Unwrapping import for Vite compatibility.\n // See: https://github.com/vitejs/vite/issues/9703\n const CoinbaseWalletSDK = await (async () => {\n const { default: SDK } = await import('@coinbase/wallet-sdk')\n if (typeof SDK !== 'function' && typeof SDK.default === 'function')\n return SDK.default\n return SDK as unknown as typeof SDK.default\n })()\n\n sdk = new CoinbaseWalletSDK({\n ...parameters,\n appChainIds: config.chains.map((x) => x.id),\n })\n\n walletProvider = sdk.makeWeb3Provider({\n ...parameters,\n options: parameters.preference ?? 'all',\n })\n }\n\n return walletProvider\n },\n async isAuthorized() {\n try {\n const accounts = await this.getAccounts()\n return !!accounts.length\n } catch {\n return false\n }\n },\n async switchChain({ addEthereumChainParameter, chainId }) {\n const chain = config.chains.find((chain) => chain.id === chainId)\n if (!chain) throw new SwitchChainError(new ChainNotConfiguredError())\n\n const provider = await this.getProvider()\n\n try {\n await provider.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: numberToHex(chain.id) }],\n })\n return chain\n } catch (error) {\n // Indicates chain is not added to provider\n if ((error as ProviderRpcError).code === 4902) {\n try {\n let blockExplorerUrls: string[] | undefined\n if (addEthereumChainParameter?.blockExplorerUrls)\n blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls\n else\n blockExplorerUrls = chain.blockExplorers?.default.url\n ? [chain.blockExplorers?.default.url]\n : []\n\n let rpcUrls: readonly string[]\n if (addEthereumChainParameter?.rpcUrls?.length)\n rpcUrls = addEthereumChainParameter.rpcUrls\n else rpcUrls = [chain.rpcUrls.default?.http[0] ?? '']\n\n const addEthereumChain = {\n blockExplorerUrls,\n chainId: numberToHex(chainId),\n chainName: addEthereumChainParameter?.chainName ?? chain.name,\n iconUrls: addEthereumChainParameter?.iconUrls,\n nativeCurrency:\n addEthereumChainParameter?.nativeCurrency ??\n chain.nativeCurrency,\n rpcUrls,\n } satisfies AddEthereumChainParameter\n\n await provider.request({\n method: 'wallet_addEthereumChain',\n params: [addEthereumChain],\n })\n\n return chain\n } catch (error) {\n throw new UserRejectedRequestError(error as Error)\n }\n }\n\n throw new SwitchChainError(error as Error)\n }\n },\n onAccountsChanged(accounts) {\n if (accounts.length === 0) this.onDisconnect()\n else\n config.emitter.emit('change', {\n accounts: accounts.map((x) => getAddress(x)),\n })\n },\n onChainChanged(chain) {\n const chainId = Number(chain)\n config.emitter.emit('change', { chainId })\n },\n async onDisconnect(_error) {\n config.emitter.emit('disconnect')\n\n const provider = await this.getProvider()\n if (accountsChanged) {\n provider.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n },\n }))\n}\n\ntype Version3Parameters = Mutable<\n Omit<\n ConstructorParameters[0],\n 'reloadOnDisconnect' // remove property since TSDoc says default is `true`\n >\n> & {\n /**\n * Fallback Ethereum JSON RPC URL\n * @default \"\"\n */\n jsonRpcUrl?: string | undefined\n /**\n * Fallback Ethereum Chain ID\n * @default 1\n */\n chainId?: number | undefined\n /**\n * Whether or not to reload dapp automatically after disconnect.\n * @default false\n */\n reloadOnDisconnect?: boolean | undefined\n}\n\nfunction version3(parameters: Version3Parameters) {\n const reloadOnDisconnect = false\n\n type Provider = CBW_Provider\n\n let sdk: CBW_SDK | undefined\n let walletProvider: Provider | undefined\n\n let accountsChanged: Connector['onAccountsChanged'] | undefined\n let chainChanged: Connector['onChainChanged'] | undefined\n let disconnect: Connector['onDisconnect'] | undefined\n\n return createConnector((config) => ({\n id: 'coinbaseWalletSDK',\n name: 'Coinbase Wallet',\n supportsSimulation: true,\n type: coinbaseWallet.type,\n async connect({ chainId } = {}) {\n try {\n const provider = await this.getProvider()\n const accounts = (\n (await provider.request({\n method: 'eth_requestAccounts',\n })) as string[]\n ).map((x) => getAddress(x))\n\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect)\n }\n\n // Switch to chain if provided\n let currentChainId = await this.getChainId()\n if (chainId && currentChainId !== chainId) {\n const chain = await this.switchChain!({ chainId }).catch((error) => {\n if (error.code === UserRejectedRequestError.code) throw error\n return { id: currentChainId }\n })\n currentChainId = chain?.id ?? currentChainId\n }\n\n return { accounts, chainId: currentChainId }\n } catch (error) {\n if (\n /(user closed modal|accounts received is empty|user denied account)/i.test(\n (error as Error).message,\n )\n )\n throw new UserRejectedRequestError(error as Error)\n throw error\n }\n },\n async disconnect() {\n const provider = await this.getProvider()\n\n if (accountsChanged) {\n provider.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n\n provider.disconnect()\n provider.close()\n },\n async getAccounts() {\n const provider = await this.getProvider()\n return (\n await provider.request({\n method: 'eth_accounts',\n })\n ).map((x) => getAddress(x))\n },\n async getChainId() {\n const provider = await this.getProvider()\n const chainId = await provider.request({\n method: 'eth_chainId',\n })\n return Number(chainId)\n },\n async getProvider() {\n if (!walletProvider) {\n // Unwrapping import for Vite compatibility.\n // See: https://github.com/vitejs/vite/issues/9703\n const CoinbaseWalletSDK = await (async () => {\n const { default: SDK } = await import('cbw-sdk')\n if (typeof SDK !== 'function' && typeof SDK.default === 'function')\n return SDK.default\n return SDK as unknown as typeof SDK.default\n })()\n\n sdk = new CoinbaseWalletSDK({ ...parameters, reloadOnDisconnect })\n\n // Force types to retrieve private `walletExtension` method from the Coinbase Wallet SDK.\n const walletExtensionChainId = (\n sdk as unknown as {\n get walletExtension(): { getChainId(): number } | undefined\n }\n ).walletExtension?.getChainId()\n\n const chain =\n config.chains.find((chain) =>\n parameters.chainId\n ? chain.id === parameters.chainId\n : chain.id === walletExtensionChainId,\n ) || config.chains[0]\n const chainId = parameters.chainId || chain?.id\n const jsonRpcUrl =\n parameters.jsonRpcUrl || chain?.rpcUrls.default.http[0]\n\n walletProvider = sdk.makeWeb3Provider(jsonRpcUrl, chainId)\n }\n\n return walletProvider\n },\n async isAuthorized() {\n try {\n const accounts = await this.getAccounts()\n return !!accounts.length\n } catch {\n return false\n }\n },\n async switchChain({ addEthereumChainParameter, chainId }) {\n const chain = config.chains.find((chain) => chain.id === chainId)\n if (!chain) throw new SwitchChainError(new ChainNotConfiguredError())\n\n const provider = await this.getProvider()\n\n try {\n await provider.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: numberToHex(chain.id) }],\n })\n return chain\n } catch (error) {\n // Indicates chain is not added to provider\n if ((error as ProviderRpcError).code === 4902) {\n try {\n let blockExplorerUrls: string[] | undefined\n if (addEthereumChainParameter?.blockExplorerUrls)\n blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls\n else\n blockExplorerUrls = chain.blockExplorers?.default.url\n ? [chain.blockExplorers?.default.url]\n : []\n\n let rpcUrls: readonly string[]\n if (addEthereumChainParameter?.rpcUrls?.length)\n rpcUrls = addEthereumChainParameter.rpcUrls\n else rpcUrls = [chain.rpcUrls.default?.http[0] ?? '']\n\n const addEthereumChain = {\n blockExplorerUrls,\n chainId: numberToHex(chainId),\n chainName: addEthereumChainParameter?.chainName ?? chain.name,\n iconUrls: addEthereumChainParameter?.iconUrls,\n nativeCurrency:\n addEthereumChainParameter?.nativeCurrency ??\n chain.nativeCurrency,\n rpcUrls,\n } satisfies AddEthereumChainParameter\n\n await provider.request({\n method: 'wallet_addEthereumChain',\n params: [addEthereumChain],\n })\n\n return chain\n } catch (error) {\n throw new UserRejectedRequestError(error as Error)\n }\n }\n\n throw new SwitchChainError(error as Error)\n }\n },\n onAccountsChanged(accounts) {\n if (accounts.length === 0) this.onDisconnect()\n else\n config.emitter.emit('change', {\n accounts: accounts.map((x) => getAddress(x)),\n })\n },\n onChainChanged(chain) {\n const chainId = Number(chain)\n config.emitter.emit('change', { chainId })\n },\n async onDisconnect(_error) {\n config.emitter.emit('disconnect')\n\n const provider = await this.getProvider()\n if (accountsChanged) {\n provider.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n },\n }))\n}\n",null,"import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry(\n fn: () => Promise,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout(\n fn: ({\n signal,\n }: { signal: AbortController['signal'] | null }) => Promise,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","import type {\n MetaMaskSDK,\n MetaMaskSDKOptions,\n SDKProvider,\n} from '@metamask/sdk'\nimport {\n ChainNotConfiguredError,\n type Connector,\n createConnector,\n extractRpcUrls,\n} from '@wagmi/core'\nimport type {\n Compute,\n ExactPartial,\n RemoveUndefined,\n} from '@wagmi/core/internal'\nimport {\n type AddEthereumChainParameter,\n type Address,\n type Hex,\n type ProviderConnectInfo,\n type ProviderRpcError,\n ResourceUnavailableRpcError,\n type RpcError,\n SwitchChainError,\n UserRejectedRequestError,\n getAddress,\n hexToNumber,\n numberToHex,\n withRetry,\n withTimeout,\n} from 'viem'\n\nexport type MetaMaskParameters = Compute<\n ExactPartial>\n>\n\nmetaMask.type = 'metaMask' as const\nexport function metaMask(parameters: MetaMaskParameters = {}) {\n type Provider = SDKProvider\n type Properties = {\n onConnect(connectInfo: ProviderConnectInfo): void\n onDisplayUri(uri: string): void\n }\n type Listener = Parameters[1]\n\n let sdk: MetaMaskSDK\n let provider: Provider | undefined\n let providerPromise: Promise\n\n let accountsChanged: Connector['onAccountsChanged'] | undefined\n let chainChanged: Connector['onChainChanged'] | undefined\n let connect: Connector['onConnect'] | undefined\n let displayUri: ((uri: string) => void) | undefined\n let disconnect: Connector['onDisconnect'] | undefined\n\n return createConnector((config) => ({\n id: 'metaMaskSDK',\n name: 'MetaMask',\n type: metaMask.type,\n async setup() {\n const provider = await this.getProvider()\n if (provider && !connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect as Listener)\n }\n },\n async connect({ chainId, isReconnecting } = {}) {\n const provider = await this.getProvider()\n if (!displayUri) {\n displayUri = this.onDisplayUri\n provider.on('display_uri', displayUri as Listener)\n }\n\n let accounts: readonly Address[] = []\n if (isReconnecting) accounts = await this.getAccounts().catch(() => [])\n\n try {\n if (!accounts?.length) {\n const requestedAccounts = (await sdk.connect()) as string[]\n accounts = requestedAccounts.map((x) => getAddress(x))\n }\n\n // Switch to chain if provided\n let currentChainId = (await this.getChainId()) as number\n if (chainId && currentChainId !== chainId) {\n const chain = await this.switchChain!({ chainId }).catch((error) => {\n if (error.code === UserRejectedRequestError.code) throw error\n return { id: currentChainId }\n })\n currentChainId = chain?.id ?? currentChainId\n }\n\n if (displayUri) {\n provider.removeListener('display_uri', displayUri)\n displayUri = undefined\n }\n\n // Manage EIP-1193 event listeners\n // https://eips.ethereum.org/EIPS/eip-1193#events\n if (connect) {\n provider.removeListener('connect', connect)\n connect = undefined\n }\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged as Listener)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged as Listener)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect as Listener)\n }\n\n return { accounts, chainId: currentChainId }\n } catch (err) {\n const error = err as RpcError\n if (error.code === UserRejectedRequestError.code)\n throw new UserRejectedRequestError(error)\n if (error.code === ResourceUnavailableRpcError.code)\n throw new ResourceUnavailableRpcError(error)\n throw error\n }\n },\n async disconnect() {\n const provider = await this.getProvider()\n\n // Manage EIP-1193 event listeners\n if (accountsChanged) {\n provider.removeListener('accountsChanged', accountsChanged)\n accountsChanged = undefined\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect as Listener)\n }\n\n await sdk.terminate()\n },\n async getAccounts() {\n const provider = await this.getProvider()\n const accounts = (await provider.request({\n method: 'eth_accounts',\n })) as string[]\n return accounts.map((x) => getAddress(x))\n },\n async getChainId() {\n const provider = await this.getProvider()\n const chainId =\n provider.getChainId() ||\n (await provider?.request({ method: 'eth_chainId' }))\n return Number(chainId)\n },\n async getProvider() {\n async function initProvider() {\n // Unwrapping import for Vite compatibility.\n // See: https://github.com/vitejs/vite/issues/9703\n const MetaMaskSDK = await (async () => {\n const { default: SDK } = await import('@metamask/sdk')\n if (typeof SDK !== 'function' && typeof SDK.default === 'function')\n return SDK.default\n return SDK as unknown as typeof SDK.default\n })()\n\n sdk = new MetaMaskSDK({\n _source: 'wagmi',\n // Workaround cast since MetaMask SDK does not support `'exactOptionalPropertyTypes'`\n ...(parameters as RemoveUndefined),\n readonlyRPCMap: Object.fromEntries(\n config.chains.map((chain) => {\n const [url] = extractRpcUrls({\n chain,\n transports: config.transports,\n })\n return [chain.id, url]\n }),\n ),\n dappMetadata: parameters.dappMetadata ?? { name: 'wagmi' },\n useDeeplink: parameters.useDeeplink ?? true,\n })\n await sdk.init()\n return sdk.getProvider()!\n }\n\n if (!provider) {\n if (!providerPromise) providerPromise = initProvider()\n provider = await providerPromise\n }\n return provider!\n },\n async isAuthorized() {\n try {\n // MetaMask mobile provider sometimes fails to immediately resolve\n // JSON-RPC requests on page load\n const timeout = 200\n const accounts = await withRetry(\n () => withTimeout(() => this.getAccounts(), { timeout }),\n {\n delay: timeout + 1,\n retryCount: 3,\n },\n )\n return !!accounts.length\n } catch {\n return false\n }\n },\n async switchChain({ addEthereumChainParameter, chainId }) {\n const provider = await this.getProvider()\n\n const chain = config.chains.find((x) => x.id === chainId)\n if (!chain) throw new SwitchChainError(new ChainNotConfiguredError())\n\n try {\n await Promise.all([\n provider\n .request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: numberToHex(chainId) }],\n })\n // During `'wallet_switchEthereumChain'`, MetaMask makes a `'net_version'` RPC call to the target chain.\n // If this request fails, MetaMask does not emit the `'chainChanged'` event, but will still switch the chain.\n // To counter this behavior, we request and emit the current chain ID to confirm the chain switch either via\n // this callback or an externally emitted `'chainChanged'` event.\n // https://github.com/MetaMask/metamask-extension/issues/24247\n .then(async () => {\n const currentChainId = await this.getChainId()\n if (currentChainId === chainId)\n config.emitter.emit('change', { chainId })\n }),\n new Promise((resolve) => {\n const listener = ((data) => {\n if ('chainId' in data && data.chainId === chainId) {\n config.emitter.off('change', listener)\n resolve()\n }\n }) satisfies Parameters[1]\n config.emitter.on('change', listener)\n }),\n ])\n return chain\n } catch (err) {\n const error = err as RpcError\n\n // Indicates chain is not added to provider\n if (\n error.code === 4902 ||\n // Unwrapping for MetaMask Mobile\n // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719\n (error as ProviderRpcError<{ originalError?: { code: number } }>)\n ?.data?.originalError?.code === 4902\n ) {\n try {\n const { default: blockExplorer, ...blockExplorers } =\n chain.blockExplorers ?? {}\n let blockExplorerUrls: string[] | undefined\n if (addEthereumChainParameter?.blockExplorerUrls)\n blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls\n else if (blockExplorer)\n blockExplorerUrls = [\n blockExplorer.url,\n ...Object.values(blockExplorers).map((x) => x.url),\n ]\n\n let rpcUrls: readonly string[]\n if (addEthereumChainParameter?.rpcUrls?.length)\n rpcUrls = addEthereumChainParameter.rpcUrls\n else rpcUrls = [chain.rpcUrls.default?.http[0] ?? '']\n\n const addEthereumChain = {\n blockExplorerUrls,\n chainId: numberToHex(chainId),\n chainName: addEthereumChainParameter?.chainName ?? chain.name,\n iconUrls: addEthereumChainParameter?.iconUrls,\n nativeCurrency:\n addEthereumChainParameter?.nativeCurrency ??\n chain.nativeCurrency,\n rpcUrls,\n } satisfies AddEthereumChainParameter\n\n await provider.request({\n method: 'wallet_addEthereumChain',\n params: [addEthereumChain],\n })\n\n const currentChainId = hexToNumber(\n // Call `'eth_chainId'` directly to guard against `this.state.chainId` (via `provider.getChainId`) being stale.\n (await provider.request({ method: 'eth_chainId' })) as Hex,\n )\n if (currentChainId !== chainId)\n throw new UserRejectedRequestError(\n new Error('User rejected switch after adding network.'),\n )\n\n return chain\n } catch (error) {\n throw new UserRejectedRequestError(error as Error)\n }\n }\n\n if (error.code === UserRejectedRequestError.code)\n throw new UserRejectedRequestError(error)\n throw new SwitchChainError(error)\n }\n },\n async onAccountsChanged(accounts) {\n // Disconnect if there are no accounts\n if (accounts.length === 0) this.onDisconnect()\n // Connect if emitter is listening for connect event (e.g. is disconnected and connects through wallet interface)\n else if (config.emitter.listenerCount('connect')) {\n const chainId = (await this.getChainId()).toString()\n this.onConnect({ chainId })\n }\n // Regular change event\n else\n config.emitter.emit('change', {\n accounts: accounts.map((x) => getAddress(x)),\n })\n },\n onChainChanged(chain) {\n const chainId = Number(chain)\n config.emitter.emit('change', { chainId })\n },\n async onConnect(connectInfo) {\n const accounts = await this.getAccounts()\n if (accounts.length === 0) return\n\n const chainId = Number(connectInfo.chainId)\n config.emitter.emit('connect', { accounts, chainId })\n\n const provider = await this.getProvider()\n if (connect) {\n provider.removeListener('connect', connect)\n connect = undefined\n }\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged as Listener)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged as Listener)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect as Listener)\n }\n },\n async onDisconnect(error) {\n const provider = await this.getProvider()\n\n // If MetaMask emits a `code: 1013` error, wait for reconnection before disconnecting\n // https://github.com/MetaMask/providers/pull/120\n if (error && (error as RpcError<1013>).code === 1013) {\n if (provider && !!(await this.getAccounts()).length) return\n }\n\n config.emitter.emit('disconnect')\n\n // Manage EIP-1193 event listeners\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged as Listener)\n }\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect as Listener)\n }\n },\n onDisplayUri(uri) {\n config.emitter.emit('message', { type: 'display_uri', data: uri })\n },\n }))\n}\n",null,null,"import type { Connection, PublicKey, SendOptions, Signer, Transaction, TransactionSignature } from '@solana/web3.js';\nimport EventEmitter from 'eventemitter3';\nimport { type WalletError, WalletNotConnectedError } from './errors.js';\nimport type { SupportedTransactionVersions, TransactionOrVersionedTransaction } from './transaction.js';\n\nexport { EventEmitter };\n\nexport interface WalletAdapterEvents {\n connect(publicKey: PublicKey): void;\n disconnect(): void;\n error(error: WalletError): void;\n readyStateChange(readyState: WalletReadyState): void;\n}\n\nexport interface SendTransactionOptions extends SendOptions {\n signers?: Signer[];\n}\n\n// WalletName is a nominal type that wallet adapters should use, e.g. `'MyCryptoWallet' as WalletName<'MyCryptoWallet'>`\n// https://medium.com/@KevinBGreene/surviving-the-typescript-ecosystem-branding-and-type-tagging-6cf6e516523d\nexport type WalletName = T & { __brand__: 'WalletName' };\n\nexport interface WalletAdapterProps {\n name: WalletName;\n url: string;\n icon: string;\n readyState: WalletReadyState;\n publicKey: PublicKey | null;\n connecting: boolean;\n connected: boolean;\n supportedTransactionVersions?: SupportedTransactionVersions;\n\n autoConnect(): Promise;\n connect(): Promise;\n disconnect(): Promise;\n sendTransaction(\n transaction: TransactionOrVersionedTransaction,\n connection: Connection,\n options?: SendTransactionOptions\n ): Promise;\n}\n\nexport type WalletAdapter = WalletAdapterProps & EventEmitter;\n\n/**\n * A wallet's readiness describes a series of states that the wallet can be in,\n * depending on what kind of wallet it is. An installable wallet (eg. a browser\n * extension like Phantom) might be `Installed` if we've found the Phantom API\n * in the global scope, or `NotDetected` otherwise. A loadable, zero-install\n * runtime (eg. Torus Wallet) might simply signal that it's `Loadable`. Use this\n * metadata to personalize the wallet list for each user (eg. to show their\n * installed wallets first).\n */\nexport enum WalletReadyState {\n /**\n * User-installable wallets can typically be detected by scanning for an API\n * that they've injected into the global context. If such an API is present,\n * we consider the wallet to have been installed.\n */\n Installed = 'Installed',\n NotDetected = 'NotDetected',\n /**\n * Loadable wallets are always available to you. Since you can load them at\n * any time, it's meaningless to say that they have been detected.\n */\n Loadable = 'Loadable',\n /**\n * If a wallet is not supported on a given platform (eg. server-rendering, or\n * mobile) then it will stay in the `Unsupported` state.\n */\n Unsupported = 'Unsupported',\n}\n\nexport abstract class BaseWalletAdapter\n extends EventEmitter\n implements WalletAdapter\n{\n abstract name: WalletName;\n abstract url: string;\n abstract icon: string;\n abstract readyState: WalletReadyState;\n abstract publicKey: PublicKey | null;\n abstract connecting: boolean;\n abstract supportedTransactionVersions?: SupportedTransactionVersions;\n\n get connected() {\n return !!this.publicKey;\n }\n\n async autoConnect() {\n await this.connect();\n }\n\n abstract connect(): Promise;\n abstract disconnect(): Promise;\n\n abstract sendTransaction(\n transaction: TransactionOrVersionedTransaction,\n connection: Connection,\n options?: SendTransactionOptions\n ): Promise;\n\n protected async prepareTransaction(\n transaction: Transaction,\n connection: Connection,\n options: SendOptions = {}\n ): Promise {\n const publicKey = this.publicKey;\n if (!publicKey) throw new WalletNotConnectedError();\n\n transaction.feePayer = transaction.feePayer || publicKey;\n transaction.recentBlockhash =\n transaction.recentBlockhash ||\n (\n await connection.getLatestBlockhash({\n commitment: options.preflightCommitment,\n minContextSlot: options.minContextSlot,\n })\n ).blockhash;\n\n return transaction;\n }\n}\n\nexport function scopePollingDetectionStrategy(detect: () => boolean): void {\n // Early return when server-side rendering\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n const disposers: (() => void)[] = [];\n\n function detectAndDispose() {\n const detected = detect();\n if (detected) {\n for (const dispose of disposers) {\n dispose();\n }\n }\n }\n\n // Strategy #1: Try detecting every second.\n const interval =\n // TODO: #334 Replace with idle callback strategy.\n setInterval(detectAndDispose, 1000);\n disposers.push(() => clearInterval(interval));\n\n // Strategy #2: Detect as soon as the DOM becomes 'ready'/'interactive'.\n if (\n // Implies that `DOMContentLoaded` has not yet fired.\n document.readyState === 'loading'\n ) {\n document.addEventListener('DOMContentLoaded', detectAndDispose, { once: true });\n disposers.push(() => document.removeEventListener('DOMContentLoaded', detectAndDispose));\n }\n\n // Strategy #3: Detect after the `window` has fully loaded.\n if (\n // If the `complete` state has been reached, we're too late.\n document.readyState !== 'complete'\n ) {\n window.addEventListener('load', detectAndDispose, { once: true });\n disposers.push(() => window.removeEventListener('load', detectAndDispose));\n }\n\n // Strategy #4: Detect synchronously, now.\n detectAndDispose();\n}\n\n/**\n * Users on iOS can be redirected into a wallet's in-app browser automatically,\n * if that wallet has a universal link configured to do so\n * But should not be redirected from within a webview, eg. if they're already\n * inside a wallet's browser\n * This function can be used to identify users who are on iOS and can be redirected\n *\n * @returns true if the user can be redirected\n */\nexport function isIosAndRedirectable() {\n // SSR: return false\n if (!navigator) return false;\n\n const userAgent = navigator.userAgent.toLowerCase();\n\n // if on iOS the user agent will contain either iPhone or iPad\n // caveat: if requesting desktop site then this won't work\n const isIos = userAgent.includes('iphone') || userAgent.includes('ipad');\n\n // if in a webview then it will not include Safari\n // note that other iOS browsers also include Safari\n // so we will redirect only if Safari is also included\n const isSafari = userAgent.includes('safari');\n\n return isIos && isSafari;\n}\n","export class WalletError extends Error {\n error: any;\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n constructor(message?: string, error?: any) {\n super(message);\n this.error = error;\n }\n}\n\nexport class WalletNotReadyError extends WalletError {\n name = 'WalletNotReadyError';\n}\n\nexport class WalletLoadError extends WalletError {\n name = 'WalletLoadError';\n}\n\nexport class WalletConfigError extends WalletError {\n name = 'WalletConfigError';\n}\n\nexport class WalletConnectionError extends WalletError {\n name = 'WalletConnectionError';\n}\n\nexport class WalletDisconnectedError extends WalletError {\n name = 'WalletDisconnectedError';\n}\n\nexport class WalletDisconnectionError extends WalletError {\n name = 'WalletDisconnectionError';\n}\n\nexport class WalletAccountError extends WalletError {\n name = 'WalletAccountError';\n}\n\nexport class WalletPublicKeyError extends WalletError {\n name = 'WalletPublicKeyError';\n}\n\nexport class WalletKeypairError extends WalletError {\n name = 'WalletKeypairError';\n}\n\nexport class WalletNotConnectedError extends WalletError {\n name = 'WalletNotConnectedError';\n}\n\nexport class WalletSendTransactionError extends WalletError {\n name = 'WalletSendTransactionError';\n}\n\nexport class WalletSignTransactionError extends WalletError {\n name = 'WalletSignTransactionError';\n}\n\nexport class WalletSignMessageError extends WalletError {\n name = 'WalletSignMessageError';\n}\n\nexport class WalletSignInError extends WalletError {\n name = 'WalletSignInError';\n}\n\nexport class WalletTimeoutError extends WalletError {\n name = 'WalletTimeoutError';\n}\n\nexport class WalletWindowBlockedError extends WalletError {\n name = 'WalletWindowBlockedError';\n}\n\nexport class WalletWindowClosedError extends WalletError {\n name = 'WalletWindowClosedError';\n}\n","import type { Config, Connector } from '../createConfig.js'\nimport { deepEqual } from '../utils/deepEqual.js'\n\nexport type GetConnectorsReturnType = readonly Connector[]\n\nlet previousConnectors: readonly Connector[] = []\n\n/** https://wagmi.sh/core/api/actions/getConnectors */\nexport function getConnectors(config: Config): GetConnectorsReturnType {\n const connectors = config.connectors\n if (deepEqual(previousConnectors, connectors)) return previousConnectors\n previousConnectors = connectors\n return connectors\n}\n","'use client'\n\nimport {\n type GetConnectorsReturnType,\n getConnectors,\n watchConnectors,\n} from '@wagmi/core'\nimport { useSyncExternalStore } from 'react'\n\nimport type { ConfigParameter } from '../types/properties.js'\nimport { useConfig } from './useConfig.js'\n\nexport type UseConnectorsParameters = ConfigParameter\n\nexport type UseConnectorsReturnType = GetConnectorsReturnType\n\n/** https://wagmi.sh/react/api/hooks/useConnectors */\nexport function useConnectors(\n parameters: UseConnectorsParameters = {},\n): UseConnectorsReturnType {\n const config = useConfig(parameters)\n\n return useSyncExternalStore(\n (onChange) => watchConnectors(config, { onChange }),\n () => getConnectors(config),\n () => getConnectors(config),\n )\n}\n","'use client'\n\nimport { useMutation } from '@tanstack/react-query'\nimport type { Config, ConnectErrorType, ResolvedRegister } from '@wagmi/core'\nimport type { Compute } from '@wagmi/core/internal'\nimport {\n type ConnectData,\n type ConnectMutate,\n type ConnectMutateAsync,\n type ConnectVariables,\n connectMutationOptions,\n} from '@wagmi/core/query'\nimport { useEffect } from 'react'\n\nimport type { ConfigParameter } from '../types/properties.js'\nimport type {\n UseMutationParameters,\n UseMutationReturnType,\n} from '../utils/query.js'\nimport { useConfig } from './useConfig.js'\nimport { type UseConnectorsReturnType, useConnectors } from './useConnectors.js'\n\nexport type UseConnectParameters<\n config extends Config = Config,\n context = unknown,\n> = Compute<\n ConfigParameter & {\n mutation?:\n | UseMutationParameters<\n ConnectData,\n ConnectErrorType,\n ConnectVariables,\n context\n >\n | undefined\n }\n>\n\nexport type UseConnectReturnType<\n config extends Config = Config,\n context = unknown,\n> = Compute<\n UseMutationReturnType<\n ConnectData,\n ConnectErrorType,\n ConnectVariables,\n context\n > & {\n connect: ConnectMutate\n connectAsync: ConnectMutateAsync\n connectors: Compute\n }\n>\n\n/** https://wagmi.sh/react/api/hooks/useConnect */\nexport function useConnect<\n config extends Config = ResolvedRegister['config'],\n context = unknown,\n>(\n parameters: UseConnectParameters = {},\n): UseConnectReturnType {\n const { mutation } = parameters\n\n const config = useConfig(parameters)\n\n const mutationOptions = connectMutationOptions(config)\n const { mutate, mutateAsync, ...result } = useMutation({\n ...mutation,\n ...mutationOptions,\n })\n\n // Reset mutation back to an idle state when the connector disconnects.\n useEffect(() => {\n return config.subscribe(\n ({ status }) => status,\n (status, previousStatus) => {\n if (previousStatus === 'connected' && status === 'disconnected')\n result.reset()\n },\n )\n }, [config, result.reset])\n\n return {\n ...result,\n connect: mutate,\n connectAsync: mutateAsync,\n connectors: useConnectors({ config }),\n }\n}\n","import type { MutationOptions } from '@tanstack/query-core'\n\nimport {\n type ConnectErrorType,\n type ConnectParameters,\n type ConnectReturnType,\n connect,\n} from '../actions/connect.js'\nimport type { Config } from '../createConfig.js'\n\nimport type { Mutate, MutateAsync } from './types.js'\n\nexport function connectMutationOptions(config: config) {\n return {\n mutationFn(variables) {\n return connect(config, variables)\n },\n mutationKey: ['connect'],\n } as const satisfies MutationOptions<\n ConnectData,\n ConnectErrorType,\n ConnectVariables\n >\n}\n\nexport type ConnectData = ConnectReturnType\n\nexport type ConnectVariables = ConnectParameters\n\nexport type ConnectMutate = Mutate<\n ConnectData,\n ConnectErrorType,\n ConnectVariables,\n context\n>\n\nexport type ConnectMutateAsync<\n config extends Config,\n context = unknown,\n> = MutateAsync<\n ConnectData,\n ConnectErrorType,\n ConnectVariables,\n context\n>\n","import type { CoinbaseWalletParameters } from 'wagmi/connectors';\nimport { LiFiToolLogo } from '../icons/lifi.js';\n\nexport const defaultCoinbaseConfig: CoinbaseWalletParameters = {\n appName: 'LI.FI',\n appLogoUrl: LiFiToolLogo,\n};\n","import type { MetaMaskParameters } from 'wagmi/connectors';\nimport { LiFiToolLogo } from '../icons/lifi.js';\n\nexport const defaultMetaMaskConfig: MetaMaskParameters = {\n dappMetadata: {\n name: 'LI.FI',\n url:\n typeof window !== 'undefined'\n ? (window as any)?.location.href\n : 'https://li.fi/',\n base64Icon: LiFiToolLogo,\n },\n};\n","import type { WalletConnectParameters } from 'wagmi/connectors';\n\nexport const defaultWalletConnectConfig: WalletConnectParameters = {\n projectId: '5432e3507d41270bee46b7b85bbc2ef8',\n};\n","import { ChainType } from '@lifi/sdk';\nimport type { CreateConnectorFnExtended } from '@lifi/wallet-management';\nimport {\n createCoinbaseConnector,\n createMetaMaskConnector,\n createWalletConnectConnector,\n getWalletPriority,\n isWalletInstalled,\n} from '@lifi/wallet-management';\nimport type { Theme } from '@mui/material';\nimport { useMediaQuery } from '@mui/material';\nimport { WalletReadyState } from '@solana/wallet-adapter-base';\nimport type { Wallet } from '@solana/wallet-adapter-react';\nimport { useWallet } from '@solana/wallet-adapter-react';\nimport { useMemo } from 'react';\nimport type { Connector } from 'wagmi';\nimport { useConnect, useAccount as useWagmiAccount } from 'wagmi';\nimport { defaultCoinbaseConfig } from '../config/coinbase.js';\nimport { defaultMetaMaskConfig } from '../config/metaMask.js';\nimport { defaultWalletConnectConfig } from '../config/walletConnect.js';\nimport type { WidgetChains, WidgetWalletConfig } from '../types/widget.js';\nimport { isItemAllowed } from '../utils/item.js';\n\nexport const useWallets = (\n walletConfig?: WidgetWalletConfig,\n chains?: WidgetChains,\n) => {\n const account = useWagmiAccount();\n const { connectors } = useConnect();\n const { wallets: solanaWallets } = useWallet();\n\n const isDesktopView = useMediaQuery((theme: Theme) =>\n theme.breakpoints.up('sm'),\n );\n\n const wallets = useMemo(() => {\n const evmConnectors: (CreateConnectorFnExtended | Connector)[] =\n Array.from(connectors);\n if (\n !connectors.some((connector) =>\n connector.id.toLowerCase().includes('walletconnect'),\n )\n ) {\n evmConnectors.unshift(\n createWalletConnectConnector(\n walletConfig?.walletConnect ?? defaultWalletConnectConfig,\n ),\n );\n }\n if (\n !connectors.some((connector) =>\n connector.id.toLowerCase().includes('coinbase'),\n ) &&\n !isWalletInstalled('coinbase')\n ) {\n evmConnectors.unshift(\n createCoinbaseConnector(\n walletConfig?.coinbase ?? defaultCoinbaseConfig,\n ),\n );\n }\n if (\n !connectors.some((connector) =>\n connector.id.toLowerCase().includes('metamask'),\n ) &&\n !isWalletInstalled('metaMask')\n ) {\n evmConnectors.unshift(\n createMetaMaskConnector(\n walletConfig?.metaMask ?? defaultMetaMaskConfig,\n ),\n );\n }\n const evmInstalled = isItemAllowed(ChainType.EVM, chains?.types)\n ? evmConnectors.filter(\n (connector) =>\n isWalletInstalled(connector.id!) &&\n // We should not show already connected connectors\n account.connector?.id !== connector.id,\n )\n : [];\n const evmNotDetected = isItemAllowed(ChainType.EVM, chains?.types)\n ? evmConnectors.filter((connector) => !isWalletInstalled(connector.id!))\n : [];\n const svmInstalled = isItemAllowed(ChainType.SVM, chains?.types)\n ? solanaWallets?.filter(\n (connector) =>\n connector.adapter.readyState === WalletReadyState.Installed &&\n // We should not show already connected connectors\n !connector.adapter.connected,\n )\n : [];\n const svmNotDetected = isItemAllowed(ChainType.SVM, chains?.types)\n ? solanaWallets?.filter(\n (connector) =>\n connector.adapter.readyState !== WalletReadyState.Installed,\n )\n : [];\n\n const installedWallets = [...evmInstalled, ...svmInstalled].sort(\n walletComparator,\n );\n\n if (isDesktopView) {\n const notDetectedWallets = [...evmNotDetected, ...svmNotDetected].sort(\n walletComparator,\n );\n installedWallets.push(...notDetectedWallets);\n }\n\n return installedWallets;\n }, [\n account.connector?.id,\n chains?.types,\n connectors,\n isDesktopView,\n solanaWallets,\n walletConfig?.coinbase,\n walletConfig?.metaMask,\n walletConfig?.walletConnect,\n ]);\n\n return wallets;\n};\n\nexport const walletComparator = (\n a: CreateConnectorFnExtended | Connector | Wallet,\n b: CreateConnectorFnExtended | Connector | Wallet,\n) => {\n let aId = (a as Connector).id || (a as Wallet).adapter?.name;\n let bId = (b as Connector).id || (b as Wallet).adapter?.name;\n\n const priorityA = getWalletPriority(aId);\n const priorityB = getWalletPriority(bId);\n\n if (priorityA !== priorityB) {\n return priorityA - priorityB;\n }\n\n if (aId < bId) {\n return -1;\n }\n if (aId > bId) {\n return 1;\n }\n return 0;\n};\n","import { ChainType } from '@lifi/sdk';\nimport type { CreateConnectorFnExtended } from '@lifi/wallet-management';\nimport {\n getConnectorIcon,\n isWalletInstalledAsync,\n} from '@lifi/wallet-management';\nimport { Avatar, ListItemAvatar } from '@mui/material';\nimport type { Connector } from 'wagmi';\nimport { useConnect, useDisconnect } from 'wagmi';\nimport { ListItemButton } from '../../components/ListItemButton.js';\nimport { ListItemText } from '../../components/ListItemText.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { WidgetEvent } from '../../types/events.js';\n\ninterface EVMListItemButtonProps {\n connectedConnector?: Connector;\n connector: CreateConnectorFnExtended | Connector;\n onNotInstalled(connector: Connector): void;\n}\n\nexport const EVMListItemButton = ({\n connectedConnector,\n connector,\n onNotInstalled,\n}: EVMListItemButtonProps) => {\n const { navigateBack } = useNavigateBack();\n const emitter = useWidgetEvents();\n const { connectAsync } = useConnect();\n const { disconnectAsync } = useDisconnect();\n\n const handleEVMConnect = async () => {\n const identityCheckPassed = await isWalletInstalledAsync(\n (connector as Connector).id,\n );\n if (!identityCheckPassed) {\n onNotInstalled(connector as Connector);\n return;\n }\n if (connectedConnector) {\n await disconnectAsync({ connector: connectedConnector });\n }\n await connectAsync(\n { connector },\n {\n onSuccess(data) {\n emitter.emit(WidgetEvent.WalletConnected, {\n address: data.accounts[0],\n chainId: data.chainId,\n chainType: ChainType.EVM,\n });\n },\n },\n );\n navigateBack();\n };\n\n const connectorName: string =\n (connector as CreateConnectorFnExtended).displayName || connector.name;\n\n return (\n \n \n \n {connectorName?.[0]}\n \n \n \n \n );\n};\n",null,"import { ChainId, ChainType } from '@lifi/sdk';\nimport { Avatar, ListItemAvatar } from '@mui/material';\nimport type { Wallet } from '@solana/wallet-adapter-react';\nimport { useWallet } from '@solana/wallet-adapter-react';\nimport { ListItemButton } from '../../components/ListItemButton.js';\nimport { ListItemText } from '../../components/ListItemText.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { WidgetEvent } from '../../types/events.js';\n\ninterface SVMListItemButtonProps {\n wallet: Wallet;\n}\n\nexport const SVMListItemButton = ({ wallet }: SVMListItemButtonProps) => {\n const { navigateBack } = useNavigateBack();\n const emitter = useWidgetEvents();\n const { select, disconnect, connected } = useWallet();\n\n const connect = async () => {\n if (connected) {\n await disconnect();\n }\n select(wallet.adapter.name);\n // We use autoConnect on wallet selection\n // await solanaConnect();\n wallet.adapter.once('connect', (publicKey) => {\n emitter.emit(WidgetEvent.WalletConnected, {\n address: publicKey?.toString(),\n chainId: ChainId.SOL,\n chainType: ChainType.SVM,\n });\n });\n navigateBack();\n };\n\n return (\n \n \n \n {wallet.adapter.name[0]}\n \n \n \n \n );\n};\n","import {\n Button,\n DialogActions,\n DialogContent,\n DialogContentText,\n List,\n} from '@mui/material';\nimport type { Wallet } from '@solana/wallet-adapter-react';\nimport { useCallback, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport type { Connector } from 'wagmi';\nimport { useAccount as useWagmiAccount } from 'wagmi';\nimport { Dialog } from '../../components/Dialog.js';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useWallets } from '../../hooks/useWallets.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { EVMListItemButton } from './EVMListItemButton.js';\nimport { SVMListItemButton } from './SVMListItemButton.js';\n\nexport const SelectWalletPage = () => {\n const { t } = useTranslation();\n const { chains, walletConfig } = useWidgetConfig();\n const account = useWagmiAccount();\n const [walletIdentity, setWalletIdentity] = useState<{\n show: boolean;\n connector?: Connector;\n }>({ show: false });\n\n useHeader(t(`header.selectWallet`));\n\n const closeDialog = () => {\n setWalletIdentity((state) => ({\n ...state,\n show: false,\n }));\n };\n\n const handleNotInstalled = useCallback(async (connector: Connector) => {\n setWalletIdentity({\n show: true,\n connector,\n });\n }, []);\n\n const wallets = useWallets(walletConfig, chains);\n\n return (\n \n \n {wallets?.map((connector) =>\n (connector as Connector).id ? (\n \n ) : (\n \n ),\n )}\n \n \n \n \n {t('wallet.extensionNotFound', {\n name: walletIdentity.connector?.name,\n })}\n \n \n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2\"\n}), 'MoreHoriz');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2\"\n}), 'TurnedIn');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M15 20H5V7c0-.55-.45-1-1-1s-1 .45-1 1v13c0 1.1.9 2 2 2h10c.55 0 1-.45 1-1s-.45-1-1-1m5-4V4c0-1.1-.9-2-2-2H9c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h9c1.1 0 2-.9 2-2m-2 0H9V4h9z\"\n}), 'ContentCopyRounded');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getDividerUtilityClass(slot) {\n return generateUtilityClass('MuiDivider', slot);\n}\nconst dividerClasses = generateUtilityClasses('MuiDivider', ['root', 'absolute', 'fullWidth', 'inset', 'middle', 'flexItem', 'light', 'vertical', 'withChildren', 'withChildrenVertical', 'textAlignRight', 'textAlignLeft', 'wrapper', 'wrapperVertical']);\nexport default dividerClasses;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getListItemIconUtilityClass(slot) {\n return generateUtilityClass('MuiListItemIcon', slot);\n}\nconst listItemIconClasses = generateUtilityClasses('MuiListItemIcon', ['root', 'alignItemsFlexStart']);\nexport default listItemIconClasses;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getMenuItemUtilityClass(slot) {\n return generateUtilityClass('MuiMenuItem', slot);\n}\nconst menuItemClasses = generateUtilityClasses('MuiMenuItem', ['root', 'focusVisible', 'dense', 'disabled', 'divider', 'gutters', 'selected']);\nexport default menuItemClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"autoFocus\", \"component\", \"dense\", \"divider\", \"disableGutters\", \"focusVisibleClassName\", \"role\", \"tabIndex\", \"className\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport styled, { rootShouldForwardProp } from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport ListContext from '../List/ListContext';\nimport ButtonBase from '../ButtonBase';\nimport useEnhancedEffect from '../utils/useEnhancedEffect';\nimport useForkRef from '../utils/useForkRef';\nimport { dividerClasses } from '../Divider';\nimport { listItemIconClasses } from '../ListItemIcon';\nimport { listItemTextClasses } from '../ListItemText';\nimport menuItemClasses, { getMenuItemUtilityClass } from './menuItemClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const overridesResolver = (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.dense && styles.dense, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters];\n};\nconst useUtilityClasses = ownerState => {\n const {\n disabled,\n dense,\n divider,\n disableGutters,\n selected,\n classes\n } = ownerState;\n const slots = {\n root: ['root', dense && 'dense', disabled && 'disabled', !disableGutters && 'gutters', divider && 'divider', selected && 'selected']\n };\n const composedClasses = composeClasses(slots, getMenuItemUtilityClass, classes);\n return _extends({}, classes, composedClasses);\n};\nconst MenuItemRoot = styled(ButtonBase, {\n shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',\n name: 'MuiMenuItem',\n slot: 'Root',\n overridesResolver\n})(({\n theme,\n ownerState\n}) => _extends({}, theme.typography.body1, {\n display: 'flex',\n justifyContent: 'flex-start',\n alignItems: 'center',\n position: 'relative',\n textDecoration: 'none',\n minHeight: 48,\n paddingTop: 6,\n paddingBottom: 6,\n boxSizing: 'border-box',\n whiteSpace: 'nowrap'\n}, !ownerState.disableGutters && {\n paddingLeft: 16,\n paddingRight: 16\n}, ownerState.divider && {\n borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,\n backgroundClip: 'padding-box'\n}, {\n '&:hover': {\n textDecoration: 'none',\n backgroundColor: (theme.vars || theme).palette.action.hover,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n },\n [`&.${menuItemClasses.selected}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),\n [`&.${menuItemClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)\n }\n },\n [`&.${menuItemClasses.selected}:hover`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)\n }\n },\n [`&.${menuItemClasses.focusVisible}`]: {\n backgroundColor: (theme.vars || theme).palette.action.focus\n },\n [`&.${menuItemClasses.disabled}`]: {\n opacity: (theme.vars || theme).palette.action.disabledOpacity\n },\n [`& + .${dividerClasses.root}`]: {\n marginTop: theme.spacing(1),\n marginBottom: theme.spacing(1)\n },\n [`& + .${dividerClasses.inset}`]: {\n marginLeft: 52\n },\n [`& .${listItemTextClasses.root}`]: {\n marginTop: 0,\n marginBottom: 0\n },\n [`& .${listItemTextClasses.inset}`]: {\n paddingLeft: 36\n },\n [`& .${listItemIconClasses.root}`]: {\n minWidth: 36\n }\n}, !ownerState.dense && {\n [theme.breakpoints.up('sm')]: {\n minHeight: 'auto'\n }\n}, ownerState.dense && _extends({\n minHeight: 32,\n // https://m2.material.io/components/menus#specs > Dense\n paddingTop: 4,\n paddingBottom: 4\n}, theme.typography.body2, {\n [`& .${listItemIconClasses.root} svg`]: {\n fontSize: '1.25rem'\n }\n})));\nconst MenuItem = /*#__PURE__*/React.forwardRef(function MenuItem(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiMenuItem'\n });\n const {\n autoFocus = false,\n component = 'li',\n dense = false,\n divider = false,\n disableGutters = false,\n focusVisibleClassName,\n role = 'menuitem',\n tabIndex: tabIndexProp,\n className\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const context = React.useContext(ListContext);\n const childContext = React.useMemo(() => ({\n dense: dense || context.dense || false,\n disableGutters\n }), [context.dense, dense, disableGutters]);\n const menuItemRef = React.useRef(null);\n useEnhancedEffect(() => {\n if (autoFocus) {\n if (menuItemRef.current) {\n menuItemRef.current.focus();\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('MUI: Unable to set focus to a MenuItem whose component has not been rendered.');\n }\n }\n }, [autoFocus]);\n const ownerState = _extends({}, props, {\n dense: childContext.dense,\n divider,\n disableGutters\n });\n const classes = useUtilityClasses(props);\n const handleRef = useForkRef(menuItemRef, ref);\n let tabIndex;\n if (!props.disabled) {\n tabIndex = tabIndexProp !== undefined ? tabIndexProp : -1;\n }\n return /*#__PURE__*/_jsx(ListContext.Provider, {\n value: childContext,\n children: /*#__PURE__*/_jsx(MenuItemRoot, _extends({\n ref: handleRef,\n role: role,\n tabIndex: tabIndex,\n component: component,\n focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),\n className: clsx(classes.root, className)\n }, other, {\n ownerState: ownerState,\n classes: classes\n }))\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? MenuItem.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * If `true`, the list item is focused during the first mount.\n * Focus will also be triggered if the value changes from false to true.\n * @default false\n */\n autoFocus: PropTypes.bool,\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, compact vertical padding designed for keyboard and mouse input is used.\n * The prop defaults to the value inherited from the parent Menu component.\n * @default false\n */\n dense: PropTypes.bool,\n /**\n * @ignore\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the left and right padding is removed.\n * @default false\n */\n disableGutters: PropTypes.bool,\n /**\n * If `true`, a 1px light border is added to the bottom of the menu item.\n * @default false\n */\n divider: PropTypes.bool,\n /**\n * This prop can help identify which element has keyboard focus.\n * The class name will be applied when the element gains the focus through keyboard interaction.\n * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).\n * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/HEAD/explainer.md).\n * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components\n * if needed.\n */\n focusVisibleClassName: PropTypes.string,\n /**\n * @ignore\n */\n role: PropTypes /* @typescript-to-proptypes-ignore */.string,\n /**\n * If `true`, the component is selected.\n * @default false\n */\n selected: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * @default 0\n */\n tabIndex: PropTypes.number\n} : void 0;\nexport default MenuItem;","import ownerDocument from '@mui/utils/ownerDocument';\nexport default ownerDocument;","import getScrollbarSize from '@mui/utils/getScrollbarSize';\nexport default getScrollbarSize;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"actions\", \"autoFocus\", \"autoFocusItem\", \"children\", \"className\", \"disabledItemsFocusable\", \"disableListWrap\", \"onKeyDown\", \"variant\"];\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport ownerDocument from '../utils/ownerDocument';\nimport List from '../List';\nimport getScrollbarSize from '../utils/getScrollbarSize';\nimport useForkRef from '../utils/useForkRef';\nimport useEnhancedEffect from '../utils/useEnhancedEffect';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction nextItem(list, item, disableListWrap) {\n if (list === item) {\n return list.firstChild;\n }\n if (item && item.nextElementSibling) {\n return item.nextElementSibling;\n }\n return disableListWrap ? null : list.firstChild;\n}\nfunction previousItem(list, item, disableListWrap) {\n if (list === item) {\n return disableListWrap ? list.firstChild : list.lastChild;\n }\n if (item && item.previousElementSibling) {\n return item.previousElementSibling;\n }\n return disableListWrap ? null : list.lastChild;\n}\nfunction textCriteriaMatches(nextFocus, textCriteria) {\n if (textCriteria === undefined) {\n return true;\n }\n let text = nextFocus.innerText;\n if (text === undefined) {\n // jsdom doesn't support innerText\n text = nextFocus.textContent;\n }\n text = text.trim().toLowerCase();\n if (text.length === 0) {\n return false;\n }\n if (textCriteria.repeating) {\n return text[0] === textCriteria.keys[0];\n }\n return text.indexOf(textCriteria.keys.join('')) === 0;\n}\nfunction moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {\n let wrappedOnce = false;\n let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);\n while (nextFocus) {\n // Prevent infinite loop.\n if (nextFocus === list.firstChild) {\n if (wrappedOnce) {\n return false;\n }\n wrappedOnce = true;\n }\n\n // Same logic as useAutocomplete.js\n const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';\n if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {\n // Move to the next element.\n nextFocus = traversalFunction(list, nextFocus, disableListWrap);\n } else {\n nextFocus.focus();\n return true;\n }\n }\n return false;\n}\n\n/**\n * A permanently displayed menu following https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/.\n * It's exposed to help customization of the [`Menu`](/material-ui/api/menu/) component if you\n * use it separately you need to move focus into the component manually. Once\n * the focus is placed inside the component it is fully keyboard accessible.\n */\nconst MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) {\n const {\n // private\n // eslint-disable-next-line react/prop-types\n actions,\n autoFocus = false,\n autoFocusItem = false,\n children,\n className,\n disabledItemsFocusable = false,\n disableListWrap = false,\n onKeyDown,\n variant = 'selectedMenu'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const listRef = React.useRef(null);\n const textCriteriaRef = React.useRef({\n keys: [],\n repeating: true,\n previousKeyMatched: true,\n lastTime: null\n });\n useEnhancedEffect(() => {\n if (autoFocus) {\n listRef.current.focus();\n }\n }, [autoFocus]);\n React.useImperativeHandle(actions, () => ({\n adjustStyleForScrollbar: (containerElement, {\n direction\n }) => {\n // Let's ignore that piece of logic if users are already overriding the width\n // of the menu.\n const noExplicitWidth = !listRef.current.style.width;\n if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {\n const scrollbarSize = `${getScrollbarSize(ownerDocument(containerElement))}px`;\n listRef.current.style[direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;\n listRef.current.style.width = `calc(100% + ${scrollbarSize})`;\n }\n return listRef.current;\n }\n }), []);\n const handleKeyDown = event => {\n const list = listRef.current;\n const key = event.key;\n /**\n * @type {Element} - will always be defined since we are in a keydown handler\n * attached to an element. A keydown event is either dispatched to the activeElement\n * or document.body or document.documentElement. Only the first case will\n * trigger this specific handler.\n */\n const currentFocus = ownerDocument(list).activeElement;\n if (key === 'ArrowDown') {\n // Prevent scroll of the page\n event.preventDefault();\n moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);\n } else if (key === 'ArrowUp') {\n event.preventDefault();\n moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);\n } else if (key === 'Home') {\n event.preventDefault();\n moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);\n } else if (key === 'End') {\n event.preventDefault();\n moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);\n } else if (key.length === 1) {\n const criteria = textCriteriaRef.current;\n const lowerKey = key.toLowerCase();\n const currTime = performance.now();\n if (criteria.keys.length > 0) {\n // Reset\n if (currTime - criteria.lastTime > 500) {\n criteria.keys = [];\n criteria.repeating = true;\n criteria.previousKeyMatched = true;\n } else if (criteria.repeating && lowerKey !== criteria.keys[0]) {\n criteria.repeating = false;\n }\n }\n criteria.lastTime = currTime;\n criteria.keys.push(lowerKey);\n const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);\n if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {\n event.preventDefault();\n } else {\n criteria.previousKeyMatched = false;\n }\n }\n if (onKeyDown) {\n onKeyDown(event);\n }\n };\n const handleRef = useForkRef(listRef, ref);\n\n /**\n * the index of the item should receive focus\n * in a `variant=\"selectedMenu\"` it's the first `selected` item\n * otherwise it's the very first item.\n */\n let activeItemIndex = -1;\n // since we inject focus related props into children we have to do a lookahead\n // to check if there is a `selected` item. We're looking for the last `selected`\n // item and use the first valid item as a fallback\n React.Children.forEach(children, (child, index) => {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n if (activeItemIndex === index) {\n activeItemIndex += 1;\n if (activeItemIndex >= children.length) {\n // there are no focusable items within the list.\n activeItemIndex = -1;\n }\n }\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"MUI: The Menu component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n if (!child.props.disabled) {\n if (variant === 'selectedMenu' && child.props.selected) {\n activeItemIndex = index;\n } else if (activeItemIndex === -1) {\n activeItemIndex = index;\n }\n }\n if (activeItemIndex === index && (child.props.disabled || child.props.muiSkipListHighlight || child.type.muiSkipListHighlight)) {\n activeItemIndex += 1;\n if (activeItemIndex >= children.length) {\n // there are no focusable items within the list.\n activeItemIndex = -1;\n }\n }\n });\n const items = React.Children.map(children, (child, index) => {\n if (index === activeItemIndex) {\n const newChildProps = {};\n if (autoFocusItem) {\n newChildProps.autoFocus = true;\n }\n if (child.props.tabIndex === undefined && variant === 'selectedMenu') {\n newChildProps.tabIndex = 0;\n }\n return /*#__PURE__*/React.cloneElement(child, newChildProps);\n }\n return child;\n });\n return /*#__PURE__*/_jsx(List, _extends({\n role: \"menu\",\n ref: handleRef,\n className: className,\n onKeyDown: handleKeyDown,\n tabIndex: autoFocus ? 0 : -1\n }, other, {\n children: items\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? MenuList.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * If `true`, will focus the `[role=\"menu\"]` container and move into tab order.\n * @default false\n */\n autoFocus: PropTypes.bool,\n /**\n * If `true`, will focus the first menuitem if `variant=\"menu\"` or selected item\n * if `variant=\"selectedMenu\"`.\n * @default false\n */\n autoFocusItem: PropTypes.bool,\n /**\n * MenuList contents, normally `MenuItem`s.\n */\n children: PropTypes.node,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * If `true`, will allow focus on disabled items.\n * @default false\n */\n disabledItemsFocusable: PropTypes.bool,\n /**\n * If `true`, the menu items will not wrap focus.\n * @default false\n */\n disableListWrap: PropTypes.bool,\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n /**\n * The variant to use. Use `menu` to prevent selected items from impacting the initial focus\n * and the vertical alignment relative to the anchor element.\n * @default 'selectedMenu'\n */\n variant: PropTypes.oneOf(['menu', 'selectedMenu'])\n} : void 0;\nexport default MenuList;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getPopoverUtilityClass(slot) {\n return generateUtilityClass('MuiPopover', slot);\n}\nconst popoverClasses = generateUtilityClasses('MuiPopover', ['root', 'paper']);\nexport default popoverClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"onEntering\"],\n _excluded2 = [\"action\", \"anchorEl\", \"anchorOrigin\", \"anchorPosition\", \"anchorReference\", \"children\", \"className\", \"container\", \"elevation\", \"marginThreshold\", \"open\", \"PaperProps\", \"slots\", \"slotProps\", \"transformOrigin\", \"TransitionComponent\", \"transitionDuration\", \"TransitionProps\", \"disableScrollLock\"],\n _excluded3 = [\"slotProps\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport HTMLElementType from '@mui/utils/HTMLElementType';\nimport refType from '@mui/utils/refType';\nimport elementTypeAcceptingRef from '@mui/utils/elementTypeAcceptingRef';\nimport integerPropType from '@mui/utils/integerPropType';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport useSlotProps from '@mui/utils/useSlotProps';\nimport isHostComponent from '@mui/utils/isHostComponent';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport debounce from '../utils/debounce';\nimport ownerDocument from '../utils/ownerDocument';\nimport ownerWindow from '../utils/ownerWindow';\nimport useForkRef from '../utils/useForkRef';\nimport Grow from '../Grow';\nimport Modal from '../Modal';\nimport PaperBase from '../Paper';\nimport { getPopoverUtilityClass } from './popoverClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport function getOffsetTop(rect, vertical) {\n let offset = 0;\n if (typeof vertical === 'number') {\n offset = vertical;\n } else if (vertical === 'center') {\n offset = rect.height / 2;\n } else if (vertical === 'bottom') {\n offset = rect.height;\n }\n return offset;\n}\nexport function getOffsetLeft(rect, horizontal) {\n let offset = 0;\n if (typeof horizontal === 'number') {\n offset = horizontal;\n } else if (horizontal === 'center') {\n offset = rect.width / 2;\n } else if (horizontal === 'right') {\n offset = rect.width;\n }\n return offset;\n}\nfunction getTransformOriginValue(transformOrigin) {\n return [transformOrigin.horizontal, transformOrigin.vertical].map(n => typeof n === 'number' ? `${n}px` : n).join(' ');\n}\nfunction resolveAnchorEl(anchorEl) {\n return typeof anchorEl === 'function' ? anchorEl() : anchorEl;\n}\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root'],\n paper: ['paper']\n };\n return composeClasses(slots, getPopoverUtilityClass, classes);\n};\nexport const PopoverRoot = styled(Modal, {\n name: 'MuiPopover',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({});\nexport const PopoverPaper = styled(PaperBase, {\n name: 'MuiPopover',\n slot: 'Paper',\n overridesResolver: (props, styles) => styles.paper\n})({\n position: 'absolute',\n overflowY: 'auto',\n overflowX: 'hidden',\n // So we see the popover when it's empty.\n // It's most likely on issue on userland.\n minWidth: 16,\n minHeight: 16,\n maxWidth: 'calc(100% - 32px)',\n maxHeight: 'calc(100% - 32px)',\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0\n});\nconst Popover = /*#__PURE__*/React.forwardRef(function Popover(inProps, ref) {\n var _slotProps$paper, _slots$root, _slots$paper;\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiPopover'\n });\n const {\n action,\n anchorEl,\n anchorOrigin = {\n vertical: 'top',\n horizontal: 'left'\n },\n anchorPosition,\n anchorReference = 'anchorEl',\n children,\n className,\n container: containerProp,\n elevation = 8,\n marginThreshold = 16,\n open,\n PaperProps: PaperPropsProp = {},\n slots,\n slotProps,\n transformOrigin = {\n vertical: 'top',\n horizontal: 'left'\n },\n TransitionComponent = Grow,\n transitionDuration: transitionDurationProp = 'auto',\n TransitionProps: {\n onEntering\n } = {},\n disableScrollLock = false\n } = props,\n TransitionProps = _objectWithoutPropertiesLoose(props.TransitionProps, _excluded),\n other = _objectWithoutPropertiesLoose(props, _excluded2);\n const externalPaperSlotProps = (_slotProps$paper = slotProps == null ? void 0 : slotProps.paper) != null ? _slotProps$paper : PaperPropsProp;\n const paperRef = React.useRef();\n const handlePaperRef = useForkRef(paperRef, externalPaperSlotProps.ref);\n const ownerState = _extends({}, props, {\n anchorOrigin,\n anchorReference,\n elevation,\n marginThreshold,\n externalPaperSlotProps,\n transformOrigin,\n TransitionComponent,\n transitionDuration: transitionDurationProp,\n TransitionProps\n });\n const classes = useUtilityClasses(ownerState);\n\n // Returns the top/left offset of the position\n // to attach to on the anchor element (or body if none is provided)\n const getAnchorOffset = React.useCallback(() => {\n if (anchorReference === 'anchorPosition') {\n if (process.env.NODE_ENV !== 'production') {\n if (!anchorPosition) {\n console.error('MUI: You need to provide a `anchorPosition` prop when using ' + '.');\n }\n }\n return anchorPosition;\n }\n const resolvedAnchorEl = resolveAnchorEl(anchorEl);\n\n // If an anchor element wasn't provided, just use the parent body element of this Popover\n const anchorElement = resolvedAnchorEl && resolvedAnchorEl.nodeType === 1 ? resolvedAnchorEl : ownerDocument(paperRef.current).body;\n const anchorRect = anchorElement.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'production') {\n const box = anchorElement.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n console.warn(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n }\n return {\n top: anchorRect.top + getOffsetTop(anchorRect, anchorOrigin.vertical),\n left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal)\n };\n }, [anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference]);\n\n // Returns the base transform origin using the element\n const getTransformOrigin = React.useCallback(elemRect => {\n return {\n vertical: getOffsetTop(elemRect, transformOrigin.vertical),\n horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal)\n };\n }, [transformOrigin.horizontal, transformOrigin.vertical]);\n const getPositioningStyle = React.useCallback(element => {\n const elemRect = {\n width: element.offsetWidth,\n height: element.offsetHeight\n };\n\n // Get the transform origin point on the element itself\n const elemTransformOrigin = getTransformOrigin(elemRect);\n if (anchorReference === 'none') {\n return {\n top: null,\n left: null,\n transformOrigin: getTransformOriginValue(elemTransformOrigin)\n };\n }\n\n // Get the offset of the anchoring element\n const anchorOffset = getAnchorOffset();\n\n // Calculate element positioning\n let top = anchorOffset.top - elemTransformOrigin.vertical;\n let left = anchorOffset.left - elemTransformOrigin.horizontal;\n const bottom = top + elemRect.height;\n const right = left + elemRect.width;\n\n // Use the parent window of the anchorEl if provided\n const containerWindow = ownerWindow(resolveAnchorEl(anchorEl));\n\n // Window thresholds taking required margin into account\n const heightThreshold = containerWindow.innerHeight - marginThreshold;\n const widthThreshold = containerWindow.innerWidth - marginThreshold;\n\n // Check if the vertical axis needs shifting\n if (marginThreshold !== null && top < marginThreshold) {\n const diff = top - marginThreshold;\n top -= diff;\n elemTransformOrigin.vertical += diff;\n } else if (marginThreshold !== null && bottom > heightThreshold) {\n const diff = bottom - heightThreshold;\n top -= diff;\n elemTransformOrigin.vertical += diff;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (elemRect.height > heightThreshold && elemRect.height && heightThreshold) {\n console.error(['MUI: The popover component is too tall.', `Some part of it can not be seen on the screen (${elemRect.height - heightThreshold}px).`, 'Please consider adding a `max-height` to improve the user-experience.'].join('\\n'));\n }\n }\n\n // Check if the horizontal axis needs shifting\n if (marginThreshold !== null && left < marginThreshold) {\n const diff = left - marginThreshold;\n left -= diff;\n elemTransformOrigin.horizontal += diff;\n } else if (right > widthThreshold) {\n const diff = right - widthThreshold;\n left -= diff;\n elemTransformOrigin.horizontal += diff;\n }\n return {\n top: `${Math.round(top)}px`,\n left: `${Math.round(left)}px`,\n transformOrigin: getTransformOriginValue(elemTransformOrigin)\n };\n }, [anchorEl, anchorReference, getAnchorOffset, getTransformOrigin, marginThreshold]);\n const [isPositioned, setIsPositioned] = React.useState(open);\n const setPositioningStyles = React.useCallback(() => {\n const element = paperRef.current;\n if (!element) {\n return;\n }\n const positioning = getPositioningStyle(element);\n if (positioning.top !== null) {\n element.style.top = positioning.top;\n }\n if (positioning.left !== null) {\n element.style.left = positioning.left;\n }\n element.style.transformOrigin = positioning.transformOrigin;\n setIsPositioned(true);\n }, [getPositioningStyle]);\n React.useEffect(() => {\n if (disableScrollLock) {\n window.addEventListener('scroll', setPositioningStyles);\n }\n return () => window.removeEventListener('scroll', setPositioningStyles);\n }, [anchorEl, disableScrollLock, setPositioningStyles]);\n const handleEntering = (element, isAppearing) => {\n if (onEntering) {\n onEntering(element, isAppearing);\n }\n setPositioningStyles();\n };\n const handleExited = () => {\n setIsPositioned(false);\n };\n React.useEffect(() => {\n if (open) {\n setPositioningStyles();\n }\n });\n React.useImperativeHandle(action, () => open ? {\n updatePosition: () => {\n setPositioningStyles();\n }\n } : null, [open, setPositioningStyles]);\n React.useEffect(() => {\n if (!open) {\n return undefined;\n }\n const handleResize = debounce(() => {\n setPositioningStyles();\n });\n const containerWindow = ownerWindow(anchorEl);\n containerWindow.addEventListener('resize', handleResize);\n return () => {\n handleResize.clear();\n containerWindow.removeEventListener('resize', handleResize);\n };\n }, [anchorEl, open, setPositioningStyles]);\n let transitionDuration = transitionDurationProp;\n if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {\n transitionDuration = undefined;\n }\n\n // If the container prop is provided, use that\n // If the anchorEl prop is provided, use its parent body element as the container\n // If neither are provided let the Modal take care of choosing the container\n const container = containerProp || (anchorEl ? ownerDocument(resolveAnchorEl(anchorEl)).body : undefined);\n const RootSlot = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : PopoverRoot;\n const PaperSlot = (_slots$paper = slots == null ? void 0 : slots.paper) != null ? _slots$paper : PopoverPaper;\n const paperProps = useSlotProps({\n elementType: PaperSlot,\n externalSlotProps: _extends({}, externalPaperSlotProps, {\n style: isPositioned ? externalPaperSlotProps.style : _extends({}, externalPaperSlotProps.style, {\n opacity: 0\n })\n }),\n additionalProps: {\n elevation,\n ref: handlePaperRef\n },\n ownerState,\n className: clsx(classes.paper, externalPaperSlotProps == null ? void 0 : externalPaperSlotProps.className)\n });\n const _useSlotProps = useSlotProps({\n elementType: RootSlot,\n externalSlotProps: (slotProps == null ? void 0 : slotProps.root) || {},\n externalForwardedProps: other,\n additionalProps: {\n ref,\n slotProps: {\n backdrop: {\n invisible: true\n }\n },\n container,\n open\n },\n ownerState,\n className: clsx(classes.root, className)\n }),\n {\n slotProps: rootSlotPropsProp\n } = _useSlotProps,\n rootProps = _objectWithoutPropertiesLoose(_useSlotProps, _excluded3);\n return /*#__PURE__*/_jsx(RootSlot, _extends({}, rootProps, !isHostComponent(RootSlot) && {\n slotProps: rootSlotPropsProp,\n disableScrollLock\n }, {\n children: /*#__PURE__*/_jsx(TransitionComponent, _extends({\n appear: true,\n in: open,\n onEntering: handleEntering,\n onExited: handleExited,\n timeout: transitionDuration\n }, TransitionProps, {\n children: /*#__PURE__*/_jsx(PaperSlot, _extends({}, paperProps, {\n children: children\n }))\n }))\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Popover.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * A ref for imperative actions.\n * It currently only supports updatePosition() action.\n */\n action: refType,\n /**\n * An HTML element, [PopoverVirtualElement](/material-ui/react-popover/#virtual-element),\n * or a function that returns either.\n * It's used to set the position of the popover.\n */\n anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.func]), props => {\n if (props.open && (!props.anchorReference || props.anchorReference === 'anchorEl')) {\n const resolvedAnchorEl = resolveAnchorEl(props.anchorEl);\n if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {\n const box = resolvedAnchorEl.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else {\n return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', `It should be an Element or PopoverVirtualElement instance but it's \\`${resolvedAnchorEl}\\` instead.`].join('\\n'));\n }\n }\n return null;\n }),\n /**\n * This is the point on the anchor where the popover's\n * `anchorEl` will attach to. This is not used when the\n * anchorReference is 'anchorPosition'.\n *\n * Options:\n * vertical: [top, center, bottom];\n * horizontal: [left, center, right].\n * @default {\n * vertical: 'top',\n * horizontal: 'left',\n * }\n */\n anchorOrigin: PropTypes.shape({\n horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,\n vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired\n }),\n /**\n * This is the position that may be used to set the position of the popover.\n * The coordinates are relative to the application's client area.\n */\n anchorPosition: PropTypes.shape({\n left: PropTypes.number.isRequired,\n top: PropTypes.number.isRequired\n }),\n /**\n * This determines which anchor prop to refer to when setting\n * the position of the popover.\n * @default 'anchorEl'\n */\n anchorReference: PropTypes.oneOf(['anchorEl', 'anchorPosition', 'none']),\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * An HTML element, component instance, or function that returns either.\n * The `container` will passed to the Modal component.\n *\n * By default, it uses the body of the anchorEl's top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * Disable the scroll lock behavior.\n * @default false\n */\n disableScrollLock: PropTypes.bool,\n /**\n * The elevation of the popover.\n * @default 8\n */\n elevation: integerPropType,\n /**\n * Specifies how close to the edge of the window the popover can appear.\n * If null, the popover will not be constrained by the window.\n * @default 16\n */\n marginThreshold: PropTypes.number,\n /**\n * Callback fired when the component requests to be closed.\n * The `reason` parameter can optionally be used to control the response to `onClose`.\n */\n onClose: PropTypes.func,\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * Props applied to the [`Paper`](/material-ui/api/paper/) element.\n *\n * This prop is an alias for `slotProps.paper` and will be overriden by it if both are used.\n * @deprecated Use `slotProps.paper` instead.\n *\n * @default {}\n */\n PaperProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({\n component: elementTypeAcceptingRef\n }),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * @default {}\n */\n slotProps: PropTypes.shape({\n paper: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n *\n * @default {}\n */\n slots: PropTypes.shape({\n paper: PropTypes.elementType,\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * This is the point on the popover which\n * will attach to the anchor's origin.\n *\n * Options:\n * vertical: [top, center, bottom, x(px)];\n * horizontal: [left, center, right, x(px)].\n * @default {\n * vertical: 'top',\n * horizontal: 'left',\n * }\n */\n transformOrigin: PropTypes.shape({\n horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,\n vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired\n }),\n /**\n * The component used for the transition.\n * [Follow this guide](/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.\n * @default Grow\n */\n TransitionComponent: PropTypes.elementType,\n /**\n * Set to 'auto' to automatically calculate transition time based on height.\n * @default 'auto'\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n /**\n * Props applied to the transition element.\n * By default, the element is based on this [`Transition`](https://reactcommunity.org/react-transition-group/transition/) component.\n * @default {}\n */\n TransitionProps: PropTypes.object\n} : void 0;\nexport default Popover;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getMenuUtilityClass(slot) {\n return generateUtilityClass('MuiMenu', slot);\n}\nconst menuClasses = generateUtilityClasses('MuiMenu', ['root', 'paper', 'list']);\nexport default menuClasses;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"onEntering\"],\n _excluded2 = [\"autoFocus\", \"children\", \"className\", \"disableAutoFocusItem\", \"MenuListProps\", \"onClose\", \"open\", \"PaperProps\", \"PopoverClasses\", \"transitionDuration\", \"TransitionProps\", \"variant\", \"slots\", \"slotProps\"];\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport HTMLElementType from '@mui/utils/HTMLElementType';\nimport { useRtl } from '@mui/system/RtlProvider';\nimport useSlotProps from '@mui/utils/useSlotProps';\nimport MenuList from '../MenuList';\nimport Popover, { PopoverPaper } from '../Popover';\nimport styled, { rootShouldForwardProp } from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport { getMenuUtilityClass } from './menuClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst RTL_ORIGIN = {\n vertical: 'top',\n horizontal: 'right'\n};\nconst LTR_ORIGIN = {\n vertical: 'top',\n horizontal: 'left'\n};\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root'],\n paper: ['paper'],\n list: ['list']\n };\n return composeClasses(slots, getMenuUtilityClass, classes);\n};\nconst MenuRoot = styled(Popover, {\n shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',\n name: 'MuiMenu',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({});\nexport const MenuPaper = styled(PopoverPaper, {\n name: 'MuiMenu',\n slot: 'Paper',\n overridesResolver: (props, styles) => styles.paper\n})({\n // specZ: The maximum height of a simple menu should be one or more rows less than the view\n // height. This ensures a tappable area outside of the simple menu with which to dismiss\n // the menu.\n maxHeight: 'calc(100% - 96px)',\n // Add iOS momentum scrolling for iOS < 13.0\n WebkitOverflowScrolling: 'touch'\n});\nconst MenuMenuList = styled(MenuList, {\n name: 'MuiMenu',\n slot: 'List',\n overridesResolver: (props, styles) => styles.list\n})({\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0\n});\nconst Menu = /*#__PURE__*/React.forwardRef(function Menu(inProps, ref) {\n var _slots$paper, _slotProps$paper;\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiMenu'\n });\n const {\n autoFocus = true,\n children,\n className,\n disableAutoFocusItem = false,\n MenuListProps = {},\n onClose,\n open,\n PaperProps = {},\n PopoverClasses,\n transitionDuration = 'auto',\n TransitionProps: {\n onEntering\n } = {},\n variant = 'selectedMenu',\n slots = {},\n slotProps = {}\n } = props,\n TransitionProps = _objectWithoutPropertiesLoose(props.TransitionProps, _excluded),\n other = _objectWithoutPropertiesLoose(props, _excluded2);\n const isRtl = useRtl();\n const ownerState = _extends({}, props, {\n autoFocus,\n disableAutoFocusItem,\n MenuListProps,\n onEntering,\n PaperProps,\n transitionDuration,\n TransitionProps,\n variant\n });\n const classes = useUtilityClasses(ownerState);\n const autoFocusItem = autoFocus && !disableAutoFocusItem && open;\n const menuListActionsRef = React.useRef(null);\n const handleEntering = (element, isAppearing) => {\n if (menuListActionsRef.current) {\n menuListActionsRef.current.adjustStyleForScrollbar(element, {\n direction: isRtl ? 'rtl' : 'ltr'\n });\n }\n if (onEntering) {\n onEntering(element, isAppearing);\n }\n };\n const handleListKeyDown = event => {\n if (event.key === 'Tab') {\n event.preventDefault();\n if (onClose) {\n onClose(event, 'tabKeyDown');\n }\n }\n };\n\n /**\n * the index of the item should receive focus\n * in a `variant=\"selectedMenu\"` it's the first `selected` item\n * otherwise it's the very first item.\n */\n let activeItemIndex = -1;\n // since we inject focus related props into children we have to do a lookahead\n // to check if there is a `selected` item. We're looking for the last `selected`\n // item and use the first valid item as a fallback\n React.Children.map(children, (child, index) => {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"MUI: The Menu component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n if (!child.props.disabled) {\n if (variant === 'selectedMenu' && child.props.selected) {\n activeItemIndex = index;\n } else if (activeItemIndex === -1) {\n activeItemIndex = index;\n }\n }\n });\n const PaperSlot = (_slots$paper = slots.paper) != null ? _slots$paper : MenuPaper;\n const paperExternalSlotProps = (_slotProps$paper = slotProps.paper) != null ? _slotProps$paper : PaperProps;\n const rootSlotProps = useSlotProps({\n elementType: slots.root,\n externalSlotProps: slotProps.root,\n ownerState,\n className: [classes.root, className]\n });\n const paperSlotProps = useSlotProps({\n elementType: PaperSlot,\n externalSlotProps: paperExternalSlotProps,\n ownerState,\n className: classes.paper\n });\n return /*#__PURE__*/_jsx(MenuRoot, _extends({\n onClose: onClose,\n anchorOrigin: {\n vertical: 'bottom',\n horizontal: isRtl ? 'right' : 'left'\n },\n transformOrigin: isRtl ? RTL_ORIGIN : LTR_ORIGIN,\n slots: {\n paper: PaperSlot,\n root: slots.root\n },\n slotProps: {\n root: rootSlotProps,\n paper: paperSlotProps\n },\n open: open,\n ref: ref,\n transitionDuration: transitionDuration,\n TransitionProps: _extends({\n onEntering: handleEntering\n }, TransitionProps),\n ownerState: ownerState\n }, other, {\n classes: PopoverClasses,\n children: /*#__PURE__*/_jsx(MenuMenuList, _extends({\n onKeyDown: handleListKeyDown,\n actions: menuListActionsRef,\n autoFocus: autoFocus && (activeItemIndex === -1 || disableAutoFocusItem),\n autoFocusItem: autoFocusItem,\n variant: variant\n }, MenuListProps, {\n className: clsx(classes.list, MenuListProps.className),\n children: children\n }))\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Menu.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * An HTML element, or a function that returns one.\n * It's used to set the position of the menu.\n */\n anchorEl: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * If `true` (Default) will focus the `[role=\"menu\"]` if no focusable child is found. Disabled\n * children are not focusable. If you set this prop to `false` focus will be placed\n * on the parent modal container. This has severe accessibility implications\n * and should only be considered if you manage focus otherwise.\n * @default true\n */\n autoFocus: PropTypes.bool,\n /**\n * Menu contents, normally `MenuItem`s.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * When opening the menu will not focus the active item but the `[role=\"menu\"]`\n * unless `autoFocus` is also set to `false`. Not using the default means not\n * following WAI-ARIA authoring practices. Please be considerate about possible\n * accessibility implications.\n * @default false\n */\n disableAutoFocusItem: PropTypes.bool,\n /**\n * Props applied to the [`MenuList`](/material-ui/api/menu-list/) element.\n * @default {}\n */\n MenuListProps: PropTypes.object,\n /**\n * Callback fired when the component requests to be closed.\n *\n * @param {object} event The event source of the callback.\n * @param {string} reason Can be: `\"escapeKeyDown\"`, `\"backdropClick\"`, `\"tabKeyDown\"`.\n */\n onClose: PropTypes.func,\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * @ignore\n */\n PaperProps: PropTypes.object,\n /**\n * `classes` prop applied to the [`Popover`](/material-ui/api/popover/) element.\n */\n PopoverClasses: PropTypes.object,\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * @default {}\n */\n slotProps: PropTypes.shape({\n paper: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n *\n * @default {}\n */\n slots: PropTypes.shape({\n paper: PropTypes.elementType,\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The length of the transition in `ms`, or 'auto'\n * @default 'auto'\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n /**\n * Props applied to the transition element.\n * By default, the element is based on this [`Transition`](https://reactcommunity.org/react-transition-group/transition/) component.\n * @default {}\n */\n TransitionProps: PropTypes.object,\n /**\n * The variant to use. Use `menu` to prevent selected items from impacting the initial focus.\n * @default 'selectedMenu'\n */\n variant: PropTypes.oneOf(['menu', 'selectedMenu'])\n} : void 0;\nexport default Menu;","import {\n Menu as MuiMenu,\n menuClasses,\n menuItemClasses,\n styled,\n svgIconClasses,\n} from '@mui/material';\n\nexport const Menu = styled(MuiMenu)(({ theme }) => ({\n [`& .${menuClasses.paper}`]: {\n borderRadius: theme.shape.borderRadius,\n boxShadow: '0px 2px 4px rgb(0 0 0 / 8%), 0px 8px 16px rgb(0 0 0 / 8%)',\n padding: theme.spacing(2),\n [`& .${menuClasses.list}`]: {\n padding: 0,\n },\n [`& .${menuItemClasses.root}`]: {\n borderRadius: theme.shape.borderRadiusSecondary,\n padding: theme.spacing(1, 2, 1, 1),\n [`& .${svgIconClasses.root}`]: {\n fontSize: 20,\n color: theme.palette.text.primary,\n marginRight: theme.spacing(1.5),\n },\n },\n },\n}));\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-2h2zm0-4h-2V7h2z\"\n}), 'Error');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-6h2zm0-8h-2V7h2z\"\n}), 'Info');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getDrawerUtilityClass(slot) {\n return generateUtilityClass('MuiDrawer', slot);\n}\nconst drawerClasses = generateUtilityClasses('MuiDrawer', ['root', 'docked', 'paper', 'paperAnchorLeft', 'paperAnchorRight', 'paperAnchorTop', 'paperAnchorBottom', 'paperAnchorDockedLeft', 'paperAnchorDockedRight', 'paperAnchorDockedTop', 'paperAnchorDockedBottom', 'modal']);\nexport default drawerClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"BackdropProps\"],\n _excluded2 = [\"anchor\", \"BackdropProps\", \"children\", \"className\", \"elevation\", \"hideBackdrop\", \"ModalProps\", \"onClose\", \"open\", \"PaperProps\", \"SlideProps\", \"TransitionComponent\", \"transitionDuration\", \"variant\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport integerPropType from '@mui/utils/integerPropType';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { useRtl } from '@mui/system/RtlProvider';\nimport Modal from '../Modal';\nimport Slide from '../Slide';\nimport Paper from '../Paper';\nimport capitalize from '../utils/capitalize';\nimport useTheme from '../styles/useTheme';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled, { rootShouldForwardProp } from '../styles/styled';\nimport { getDrawerUtilityClass } from './drawerClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst overridesResolver = (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, (ownerState.variant === 'permanent' || ownerState.variant === 'persistent') && styles.docked, styles.modal];\n};\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n anchor,\n variant\n } = ownerState;\n const slots = {\n root: ['root'],\n docked: [(variant === 'permanent' || variant === 'persistent') && 'docked'],\n modal: ['modal'],\n paper: ['paper', `paperAnchor${capitalize(anchor)}`, variant !== 'temporary' && `paperAnchorDocked${capitalize(anchor)}`]\n };\n return composeClasses(slots, getDrawerUtilityClass, classes);\n};\nconst DrawerRoot = styled(Modal, {\n name: 'MuiDrawer',\n slot: 'Root',\n overridesResolver\n})(({\n theme\n}) => ({\n zIndex: (theme.vars || theme).zIndex.drawer\n}));\nconst DrawerDockedRoot = styled('div', {\n shouldForwardProp: rootShouldForwardProp,\n name: 'MuiDrawer',\n slot: 'Docked',\n skipVariantsResolver: false,\n overridesResolver\n})({\n flex: '0 0 auto'\n});\nconst DrawerPaper = styled(Paper, {\n name: 'MuiDrawer',\n slot: 'Paper',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.paper, styles[`paperAnchor${capitalize(ownerState.anchor)}`], ownerState.variant !== 'temporary' && styles[`paperAnchorDocked${capitalize(ownerState.anchor)}`]];\n }\n})(({\n theme,\n ownerState\n}) => _extends({\n overflowY: 'auto',\n display: 'flex',\n flexDirection: 'column',\n height: '100%',\n flex: '1 0 auto',\n zIndex: (theme.vars || theme).zIndex.drawer,\n // Add iOS momentum scrolling for iOS < 13.0\n WebkitOverflowScrolling: 'touch',\n // temporary style\n position: 'fixed',\n top: 0,\n // We disable the focus ring for mouse, touch and keyboard users.\n // At some point, it would be better to keep it for keyboard users.\n // :focus-ring CSS pseudo-class will help.\n outline: 0\n}, ownerState.anchor === 'left' && {\n left: 0\n}, ownerState.anchor === 'top' && {\n top: 0,\n left: 0,\n right: 0,\n height: 'auto',\n maxHeight: '100%'\n}, ownerState.anchor === 'right' && {\n right: 0\n}, ownerState.anchor === 'bottom' && {\n top: 'auto',\n left: 0,\n bottom: 0,\n right: 0,\n height: 'auto',\n maxHeight: '100%'\n}, ownerState.anchor === 'left' && ownerState.variant !== 'temporary' && {\n borderRight: `1px solid ${(theme.vars || theme).palette.divider}`\n}, ownerState.anchor === 'top' && ownerState.variant !== 'temporary' && {\n borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`\n}, ownerState.anchor === 'right' && ownerState.variant !== 'temporary' && {\n borderLeft: `1px solid ${(theme.vars || theme).palette.divider}`\n}, ownerState.anchor === 'bottom' && ownerState.variant !== 'temporary' && {\n borderTop: `1px solid ${(theme.vars || theme).palette.divider}`\n}));\nconst oppositeDirection = {\n left: 'right',\n right: 'left',\n top: 'down',\n bottom: 'up'\n};\nexport function isHorizontal(anchor) {\n return ['left', 'right'].indexOf(anchor) !== -1;\n}\nexport function getAnchor({\n direction\n}, anchor) {\n return direction === 'rtl' && isHorizontal(anchor) ? oppositeDirection[anchor] : anchor;\n}\n\n/**\n * The props of the [Modal](/material-ui/api/modal/) component are available\n * when `variant=\"temporary\"` is set.\n */\nconst Drawer = /*#__PURE__*/React.forwardRef(function Drawer(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiDrawer'\n });\n const theme = useTheme();\n const isRtl = useRtl();\n const defaultTransitionDuration = {\n enter: theme.transitions.duration.enteringScreen,\n exit: theme.transitions.duration.leavingScreen\n };\n const {\n anchor: anchorProp = 'left',\n BackdropProps,\n children,\n className,\n elevation = 16,\n hideBackdrop = false,\n ModalProps: {\n BackdropProps: BackdropPropsProp\n } = {},\n onClose,\n open = false,\n PaperProps = {},\n SlideProps,\n // eslint-disable-next-line react/prop-types\n TransitionComponent = Slide,\n transitionDuration = defaultTransitionDuration,\n variant = 'temporary'\n } = props,\n ModalProps = _objectWithoutPropertiesLoose(props.ModalProps, _excluded),\n other = _objectWithoutPropertiesLoose(props, _excluded2);\n\n // Let's assume that the Drawer will always be rendered on user space.\n // We use this state is order to skip the appear transition during the\n // initial mount of the component.\n const mounted = React.useRef(false);\n React.useEffect(() => {\n mounted.current = true;\n }, []);\n const anchorInvariant = getAnchor({\n direction: isRtl ? 'rtl' : 'ltr'\n }, anchorProp);\n const anchor = anchorProp;\n const ownerState = _extends({}, props, {\n anchor,\n elevation,\n open,\n variant\n }, other);\n const classes = useUtilityClasses(ownerState);\n const drawer = /*#__PURE__*/_jsx(DrawerPaper, _extends({\n elevation: variant === 'temporary' ? elevation : 0,\n square: true\n }, PaperProps, {\n className: clsx(classes.paper, PaperProps.className),\n ownerState: ownerState,\n children: children\n }));\n if (variant === 'permanent') {\n return /*#__PURE__*/_jsx(DrawerDockedRoot, _extends({\n className: clsx(classes.root, classes.docked, className),\n ownerState: ownerState,\n ref: ref\n }, other, {\n children: drawer\n }));\n }\n const slidingDrawer = /*#__PURE__*/_jsx(TransitionComponent, _extends({\n in: open,\n direction: oppositeDirection[anchorInvariant],\n timeout: transitionDuration,\n appear: mounted.current\n }, SlideProps, {\n children: drawer\n }));\n if (variant === 'persistent') {\n return /*#__PURE__*/_jsx(DrawerDockedRoot, _extends({\n className: clsx(classes.root, classes.docked, className),\n ownerState: ownerState,\n ref: ref\n }, other, {\n children: slidingDrawer\n }));\n }\n\n // variant === temporary\n return /*#__PURE__*/_jsx(DrawerRoot, _extends({\n BackdropProps: _extends({}, BackdropProps, BackdropPropsProp, {\n transitionDuration\n }),\n className: clsx(classes.root, classes.modal, className),\n open: open,\n ownerState: ownerState,\n onClose: onClose,\n hideBackdrop: hideBackdrop,\n ref: ref\n }, other, ModalProps, {\n children: slidingDrawer\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Drawer.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Side from which the drawer will appear.\n * @default 'left'\n */\n anchor: PropTypes.oneOf(['bottom', 'left', 'right', 'top']),\n /**\n * @ignore\n */\n BackdropProps: PropTypes.object,\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The elevation of the drawer.\n * @default 16\n */\n elevation: integerPropType,\n /**\n * If `true`, the backdrop is not rendered.\n * @default false\n */\n hideBackdrop: PropTypes.bool,\n /**\n * Props applied to the [`Modal`](/material-ui/api/modal/) element.\n * @default {}\n */\n ModalProps: PropTypes.object,\n /**\n * Callback fired when the component requests to be closed.\n * The `reason` parameter can optionally be used to control the response to `onClose`.\n *\n * @param {object} event The event source of the callback.\n * @param {string} reason Can be: `\"escapeKeyDown\"`, `\"backdropClick\"`.\n */\n onClose: PropTypes.func,\n /**\n * If `true`, the component is shown.\n * @default false\n */\n open: PropTypes.bool,\n /**\n * Props applied to the [`Paper`](/material-ui/api/paper/) element.\n * @default {}\n */\n PaperProps: PropTypes.object,\n /**\n * Props applied to the [`Slide`](/material-ui/api/slide/) element.\n */\n SlideProps: PropTypes.object,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n * @default {\n * enter: theme.transitions.duration.enteringScreen,\n * exit: theme.transitions.duration.leavingScreen,\n * }\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n /**\n * The variant to use.\n * @default 'temporary'\n */\n variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary'])\n} : void 0;\nexport default Drawer;","import { Drawer } from '@mui/material';\nimport {\n forwardRef,\n useCallback,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\nimport { useGetScrollableContainer } from '../../hooks/useScrollableContainer.js';\nimport { modalProps, paperProps, slotProps } from '../Dialog.js';\nimport type { BottomSheetBase, BottomSheetProps } from './types.js';\n\nexport const BottomSheet = forwardRef(\n ({ elementRef, children, open, onClose }, ref) => {\n const getContainer = useGetScrollableContainer();\n const openRef = useRef(open);\n const [drawerOpen, setDrawerOpen] = useState(open);\n\n const close = useCallback(() => {\n setDrawerOpen(false);\n openRef.current = false;\n onClose?.();\n }, [onClose]);\n\n useImperativeHandle(\n ref,\n () => ({\n isOpen: () => openRef.current,\n open: () => {\n setDrawerOpen(true);\n openRef.current = true;\n },\n close,\n }),\n [close],\n );\n\n return (\n \n {children}\n \n );\n },\n);\n","import type { Chain, ChainType } from '@lifi/sdk';\nimport { getNameServiceAddress } from '@lifi/sdk';\nimport { useMutation } from '@tanstack/react-query';\nimport { useTranslation } from 'react-i18next';\nimport { getChainTypeFromAddress } from '../utils/chainType.js';\n\nexport enum AddressType {\n Address,\n NameService,\n}\n\ntype ValidationArgs = {\n value: string;\n chainType?: ChainType;\n chain?: Chain;\n};\n\ntype ValidResponse = {\n address: string;\n addressType: AddressType;\n chainType: ChainType;\n isValid: true;\n};\n\ntype InvalidResponse = {\n error: string;\n isValid: false;\n};\n\nexport const useAddressValidation = () => {\n const { t } = useTranslation();\n\n const { mutateAsync: validateAddress, isPending: isValidating } = useMutation(\n {\n mutationFn: async ({\n value,\n chainType,\n chain,\n }: ValidationArgs): Promise => {\n try {\n if (!value) {\n throw new Error();\n }\n\n const _chainType = getChainTypeFromAddress(value);\n if (_chainType) {\n return {\n address: value,\n addressType: AddressType.Address,\n chainType: _chainType,\n isValid: true,\n };\n }\n\n const address = await getNameServiceAddress(value, chainType);\n\n if (address) {\n const _chainType = getChainTypeFromAddress(address);\n if (_chainType) {\n return {\n address: address,\n addressType: AddressType.NameService,\n chainType: _chainType,\n isValid: true,\n };\n }\n }\n\n throw new Error();\n } catch (_) {\n return {\n isValid: false,\n error: t(\n 'error.title.walletAddressInvalid',\n chain?.name\n ? { context: 'chain', chainName: chain.name }\n : undefined,\n ),\n };\n }\n },\n },\n );\n\n return {\n validateAddress,\n isValidating,\n };\n};\n","import type { ChainType } from '@lifi/types'\nimport { config } from '../config.js'\n\nexport const getNameServiceAddress = async (\n name: string,\n chainType?: ChainType\n): Promise => {\n try {\n let providers = config.get().providers\n if (chainType) {\n providers = providers.filter((provider) => provider.type === chainType)\n }\n const resolvers = providers.map((provider) => provider.resolveAddress)\n if (!resolvers.length) {\n return\n }\n const result = await Promise.any(\n resolvers.map(async (resolve) => {\n const address = await resolve(name)\n if (!address) {\n throw undefined\n }\n return address\n })\n )\n return result\n } catch (_) {\n return\n }\n}\n","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getAlertUtilityClass(slot) {\n return generateUtilityClass('MuiAlert', slot);\n}\nconst alertClasses = generateUtilityClasses('MuiAlert', ['root', 'action', 'icon', 'message', 'filled', 'colorSuccess', 'colorInfo', 'colorWarning', 'colorError', 'filledSuccess', 'filledInfo', 'filledWarning', 'filledError', 'outlined', 'outlinedSuccess', 'outlinedInfo', 'outlinedWarning', 'outlinedError', 'standard', 'standardSuccess', 'standardInfo', 'standardWarning', 'standardError']);\nexport default alertClasses;","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4C12.76,4 13.5,4.11 14.2, 4.31L15.77,2.74C14.61,2.26 13.34,2 12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0, 0 22,12M7.91,10.08L6.5,11.5L11,16L21,6L19.59,4.58L11,13.17L7.91,10.08Z\"\n}), 'SuccessOutlined');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M12 5.99L19.53 19H4.47L12 5.99M12 2L1 21h22L12 2zm1 14h-2v2h2v-2zm0-6h-2v4h2v-4z\"\n}), 'ReportProblemOutlined');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z\"\n}), 'ErrorOutline');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M11,9H13V7H11M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20, 12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10, 10 0 0,0 12,2M11,17H13V11H11V17Z\"\n}), 'InfoOutlined');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n *\n * Alias to `Clear`.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z\"\n}), 'Close');","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"action\", \"children\", \"className\", \"closeText\", \"color\", \"components\", \"componentsProps\", \"icon\", \"iconMapping\", \"onClose\", \"role\", \"severity\", \"slotProps\", \"slots\", \"variant\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { darken, lighten } from '@mui/system/colorManipulator';\nimport { styled } from '../zero-styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport useSlot from '../utils/useSlot';\nimport capitalize from '../utils/capitalize';\nimport Paper from '../Paper';\nimport alertClasses, { getAlertUtilityClass } from './alertClasses';\nimport IconButton from '../IconButton';\nimport SuccessOutlinedIcon from '../internal/svg-icons/SuccessOutlined';\nimport ReportProblemOutlinedIcon from '../internal/svg-icons/ReportProblemOutlined';\nimport ErrorOutlineIcon from '../internal/svg-icons/ErrorOutline';\nimport InfoOutlinedIcon from '../internal/svg-icons/InfoOutlined';\nimport CloseIcon from '../internal/svg-icons/Close';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n variant,\n color,\n severity,\n classes\n } = ownerState;\n const slots = {\n root: ['root', `color${capitalize(color || severity)}`, `${variant}${capitalize(color || severity)}`, `${variant}`],\n icon: ['icon'],\n message: ['message'],\n action: ['action']\n };\n return composeClasses(slots, getAlertUtilityClass, classes);\n};\nconst AlertRoot = styled(Paper, {\n name: 'MuiAlert',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.variant], styles[`${ownerState.variant}${capitalize(ownerState.color || ownerState.severity)}`]];\n }\n})(({\n theme\n}) => {\n const getColor = theme.palette.mode === 'light' ? darken : lighten;\n const getBackgroundColor = theme.palette.mode === 'light' ? lighten : darken;\n return _extends({}, theme.typography.body2, {\n backgroundColor: 'transparent',\n display: 'flex',\n padding: '6px 16px',\n variants: [...Object.entries(theme.palette).filter(([, value]) => value.main && value.light).map(([color]) => ({\n props: {\n colorSeverity: color,\n variant: 'standard'\n },\n style: {\n color: theme.vars ? theme.vars.palette.Alert[`${color}Color`] : getColor(theme.palette[color].light, 0.6),\n backgroundColor: theme.vars ? theme.vars.palette.Alert[`${color}StandardBg`] : getBackgroundColor(theme.palette[color].light, 0.9),\n [`& .${alertClasses.icon}`]: theme.vars ? {\n color: theme.vars.palette.Alert[`${color}IconColor`]\n } : {\n color: theme.palette[color].main\n }\n }\n })), ...Object.entries(theme.palette).filter(([, value]) => value.main && value.light).map(([color]) => ({\n props: {\n colorSeverity: color,\n variant: 'outlined'\n },\n style: {\n color: theme.vars ? theme.vars.palette.Alert[`${color}Color`] : getColor(theme.palette[color].light, 0.6),\n border: `1px solid ${(theme.vars || theme).palette[color].light}`,\n [`& .${alertClasses.icon}`]: theme.vars ? {\n color: theme.vars.palette.Alert[`${color}IconColor`]\n } : {\n color: theme.palette[color].main\n }\n }\n })), ...Object.entries(theme.palette).filter(([, value]) => value.main && value.dark).map(([color]) => ({\n props: {\n colorSeverity: color,\n variant: 'filled'\n },\n style: _extends({\n fontWeight: theme.typography.fontWeightMedium\n }, theme.vars ? {\n color: theme.vars.palette.Alert[`${color}FilledColor`],\n backgroundColor: theme.vars.palette.Alert[`${color}FilledBg`]\n } : {\n backgroundColor: theme.palette.mode === 'dark' ? theme.palette[color].dark : theme.palette[color].main,\n color: theme.palette.getContrastText(theme.palette[color].main)\n })\n }))]\n });\n});\nconst AlertIcon = styled('div', {\n name: 'MuiAlert',\n slot: 'Icon',\n overridesResolver: (props, styles) => styles.icon\n})({\n marginRight: 12,\n padding: '7px 0',\n display: 'flex',\n fontSize: 22,\n opacity: 0.9\n});\nconst AlertMessage = styled('div', {\n name: 'MuiAlert',\n slot: 'Message',\n overridesResolver: (props, styles) => styles.message\n})({\n padding: '8px 0',\n minWidth: 0,\n overflow: 'auto'\n});\nconst AlertAction = styled('div', {\n name: 'MuiAlert',\n slot: 'Action',\n overridesResolver: (props, styles) => styles.action\n})({\n display: 'flex',\n alignItems: 'flex-start',\n padding: '4px 0 0 16px',\n marginLeft: 'auto',\n marginRight: -8\n});\nconst defaultIconMapping = {\n success: /*#__PURE__*/_jsx(SuccessOutlinedIcon, {\n fontSize: \"inherit\"\n }),\n warning: /*#__PURE__*/_jsx(ReportProblemOutlinedIcon, {\n fontSize: \"inherit\"\n }),\n error: /*#__PURE__*/_jsx(ErrorOutlineIcon, {\n fontSize: \"inherit\"\n }),\n info: /*#__PURE__*/_jsx(InfoOutlinedIcon, {\n fontSize: \"inherit\"\n })\n};\nconst Alert = /*#__PURE__*/React.forwardRef(function Alert(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiAlert'\n });\n const {\n action,\n children,\n className,\n closeText = 'Close',\n color,\n components = {},\n componentsProps = {},\n icon,\n iconMapping = defaultIconMapping,\n onClose,\n role = 'alert',\n severity = 'success',\n slotProps = {},\n slots = {},\n variant = 'standard'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n color,\n severity,\n variant,\n colorSeverity: color || severity\n });\n const classes = useUtilityClasses(ownerState);\n const externalForwardedProps = {\n slots: _extends({\n closeButton: components.CloseButton,\n closeIcon: components.CloseIcon\n }, slots),\n slotProps: _extends({}, componentsProps, slotProps)\n };\n const [CloseButtonSlot, closeButtonProps] = useSlot('closeButton', {\n elementType: IconButton,\n externalForwardedProps,\n ownerState\n });\n const [CloseIconSlot, closeIconProps] = useSlot('closeIcon', {\n elementType: CloseIcon,\n externalForwardedProps,\n ownerState\n });\n return /*#__PURE__*/_jsxs(AlertRoot, _extends({\n role: role,\n elevation: 0,\n ownerState: ownerState,\n className: clsx(classes.root, className),\n ref: ref\n }, other, {\n children: [icon !== false ? /*#__PURE__*/_jsx(AlertIcon, {\n ownerState: ownerState,\n className: classes.icon,\n children: icon || iconMapping[severity] || defaultIconMapping[severity]\n }) : null, /*#__PURE__*/_jsx(AlertMessage, {\n ownerState: ownerState,\n className: classes.message,\n children: children\n }), action != null ? /*#__PURE__*/_jsx(AlertAction, {\n ownerState: ownerState,\n className: classes.action,\n children: action\n }) : null, action == null && onClose ? /*#__PURE__*/_jsx(AlertAction, {\n ownerState: ownerState,\n className: classes.action,\n children: /*#__PURE__*/_jsx(CloseButtonSlot, _extends({\n size: \"small\",\n \"aria-label\": closeText,\n title: closeText,\n color: \"inherit\",\n onClick: onClose\n }, closeButtonProps, {\n children: /*#__PURE__*/_jsx(CloseIconSlot, _extends({\n fontSize: \"small\"\n }, closeIconProps))\n }))\n }) : null]\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Alert.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The action to display. It renders after the message, at the end of the alert.\n */\n action: PropTypes.node,\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * Override the default label for the *close popup* icon button.\n *\n * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).\n * @default 'Close'\n */\n closeText: PropTypes.string,\n /**\n * The color of the component. Unless provided, the value is taken from the `severity` prop.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The components used for each slot inside.\n *\n * @deprecated use the `slots` prop instead. This prop will be removed in v7. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/).\n *\n * @default {}\n */\n components: PropTypes.shape({\n CloseButton: PropTypes.elementType,\n CloseIcon: PropTypes.elementType\n }),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * @deprecated use the `slotProps` prop instead. This prop will be removed in v7. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/).\n *\n * @default {}\n */\n componentsProps: PropTypes.shape({\n closeButton: PropTypes.object,\n closeIcon: PropTypes.object\n }),\n /**\n * Override the icon displayed before the children.\n * Unless provided, the icon is mapped to the value of the `severity` prop.\n * Set to `false` to remove the `icon`.\n */\n icon: PropTypes.node,\n /**\n * The component maps the `severity` prop to a range of different icons,\n * for instance success to ``.\n * If you wish to change this mapping, you can provide your own.\n * Alternatively, you can use the `icon` prop to override the icon displayed.\n */\n iconMapping: PropTypes.shape({\n error: PropTypes.node,\n info: PropTypes.node,\n success: PropTypes.node,\n warning: PropTypes.node\n }),\n /**\n * Callback fired when the component requests to be closed.\n * When provided and no `action` prop is set, a close icon button is displayed that triggers the callback when clicked.\n * @param {React.SyntheticEvent} event The event source of the callback.\n */\n onClose: PropTypes.func,\n /**\n * The ARIA role attribute of the element.\n * @default 'alert'\n */\n role: PropTypes.string,\n /**\n * The severity of the alert. This defines the color and icon used.\n * @default 'success'\n */\n severity: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes.shape({\n closeButton: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n closeIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n closeButton: PropTypes.elementType,\n closeIcon: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The variant to use.\n * @default 'standard'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['filled', 'outlined', 'standard']), PropTypes.string])\n} : void 0;\nexport default Alert;","import {\n Alert,\n Box,\n IconButton,\n List,\n Typography,\n alertClasses,\n inputBaseClasses,\n styled,\n} from '@mui/material';\nimport { ButtonTertiary } from '../../components/ButtonTertiary.js';\nimport { InputCard } from '../../components/Card/InputCard.js';\nimport { Input } from '../../components/Input.js';\nimport type { PageContainerProps } from '../../components/PageContainer.js';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { getContrastAlphaColor } from '../../utils/colors.js';\n\nexport const AddressInput = styled(Input)(({ theme }) => ({\n padding: 0,\n [`.${inputBaseClasses.input}`]: {\n padding: theme.spacing(2),\n minHeight: 48,\n },\n}));\n\nexport const BookmarkInputFields = styled(Box)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n gap: theme.spacing(2),\n width: '100%',\n}));\n\nexport const SendToWalletPageContainer = styled(\n PageContainer,\n)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n gap: theme.spacing(1),\n}));\n\ninterface FullHeightAdjustablePageContainerProps extends PageContainerProps {\n enableFullHeight?: boolean;\n}\n\nexport const FullHeightAdjustablePageContainer = styled(\n SendToWalletPageContainer,\n {\n shouldForwardProp: (prop) => prop !== 'enableFullHeight',\n },\n)(({ theme, enableFullHeight }) => ({\n justifyContent: 'space-between',\n ...(enableFullHeight && theme.container?.height === '100%'\n ? {\n justifyContent: 'space-between',\n height: '100%',\n }\n : {}),\n}));\n\nexport const SendToWalletCard = styled(InputCard)({\n display: 'flex',\n flexDirection: 'column',\n});\n\nexport const SendToWalletSheetContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n padding: theme.spacing(4, 3, 3),\n gap: theme.spacing(2),\n}));\n\nexport const SendToWalletButtonRow = styled(Box)(({ theme }) => ({\n display: 'flex',\n width: '100%',\n gap: theme.spacing(1),\n}));\n\nexport const SendToWalletIconButton = styled(ButtonTertiary)(({ theme }) => ({\n padding: theme.spacing(1.25),\n minWidth: 40,\n}));\n\nexport const IconContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n width: 80,\n height: 80,\n color:\n theme.palette.mode === 'light'\n ? theme.palette.grey[700]\n : theme.palette.grey[300],\n background:\n theme.palette.mode === 'light'\n ? theme.palette.grey[200]\n : theme.palette.grey[800],\n borderRadius: '50%',\n}));\n\nexport const SheetTitle = styled(Typography)(() => ({\n fontSize: 18,\n fontWeight: 700,\n}));\n\nexport const SheetAddressContainer = styled(Box)(() => ({\n width: '100%',\n wordWrap: 'break-word',\n}));\n\nexport const ListContainer = styled(List)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n padding: 0,\n minHeight: 400,\n}));\n\nexport const BookmarksListContainer = styled(ListContainer)(({ theme }) => ({\n ...(theme.container?.height === '100%'\n ? { minHeight: 360, height: 360, flexGrow: 1, overflow: 'auto' }\n : { minHeight: 440 }),\n}));\n\nexport const BookmarkButtonContainer = styled(Box)(({ theme }) => ({\n background: theme.palette.background.default,\n display: 'flex',\n flexDirection: 'column',\n bottom: 0,\n padding: theme.spacing(0, 3, 3),\n zIndex: 2,\n position: 'sticky',\n width: '100%',\n}));\n\nexport const EmptyContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'center',\n alignItems: 'center',\n flexGrow: 1,\n gap: theme.spacing(2),\n}));\n\nexport const ValidationAlert = styled(Alert)(({ theme }) => ({\n backgroundColor: 'transparent',\n padding: 0,\n color: theme.palette.text.primary,\n [`.${alertClasses.icon}`]: {\n padding: 0,\n color: theme.palette.error.main,\n },\n [`.${alertClasses.message}`]: { padding: theme.spacing(0.25, 0, 0, 0) },\n}));\n\nexport const OptionsMenuButton = styled(IconButton)(({ theme }) => ({\n position: 'absolute',\n top: theme.spacing(1.75),\n right: theme.spacing(2),\n '&:hover': {\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n },\n}));\n","import { Error, Info, TurnedIn } from '@mui/icons-material';\nimport { LoadingButton } from '@mui/lab';\nimport { Button, Typography } from '@mui/material';\nimport type { ChangeEvent, MutableRefObject } from 'react';\nimport { forwardRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { AlertMessage } from '../../components/AlertMessage/AlertMessage.js';\nimport { BottomSheet } from '../../components/BottomSheet/BottomSheet.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { Input } from '../../components/Input.js';\nimport { useAddressValidation } from '../../hooks/useAddressValidation.js';\nimport type { Bookmark } from '../../stores/bookmarks/types.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport {\n AddressInput,\n BookmarkInputFields,\n IconContainer,\n SendToWalletButtonRow,\n SendToWalletCard,\n SendToWalletSheetContainer,\n SheetAddressContainer,\n SheetTitle,\n ValidationAlert,\n} from './SendToWalletPage.style.js';\nimport type { BookmarkError } from './types.js';\n\ninterface BookmarkAddressProps {\n onAddBookmark: (bookmark: Bookmark) => void;\n validatedWallet?: Bookmark;\n}\n\nexport const BookmarkAddressSheet = forwardRef<\n BottomSheetBase,\n BookmarkAddressProps\n>(({ validatedWallet, onAddBookmark }, ref) => {\n const { t } = useTranslation();\n const [name, setName] = useState('');\n const [address, setAddress] = useState('');\n const [error, setError] = useState();\n const { validateAddress, isValidating } = useAddressValidation();\n const { getBookmark } = useBookmarkActions();\n\n const nameValue = name.trim() || validatedWallet?.name || '';\n const addressValue = address || validatedWallet?.address || '';\n\n const handleCancel = () => {\n setError(undefined);\n (ref as MutableRefObject).current?.close();\n };\n\n const validateWithAddressFromInput = async () => {\n const validationResult = await validateAddress({ value: address });\n if (!validationResult.isValid) {\n setError({ type: 'address', message: validationResult.error });\n return;\n }\n\n return {\n name: nameValue,\n address: validationResult.address,\n chainType: validationResult.chainType,\n };\n };\n\n const validateWithValidatedWallet = () => {\n if (error) {\n setError(undefined);\n }\n return {\n name: nameValue,\n address: validatedWallet!.address,\n chainType: validatedWallet!.chainType,\n };\n };\n\n const handleBookmark = async () => {\n if (isValidating) {\n return;\n }\n if (!nameValue) {\n setError({\n type: 'name',\n message: t('error.title.bookmarkNameRequired'),\n });\n return;\n }\n if (!addressValue) {\n setError({\n type: 'address',\n message: t('error.title.walletAddressRequired'),\n });\n return;\n }\n\n // If the validatedWallet is supplied as a prop then we should assume\n // the address has already been validated\n const validatedBookmark = validatedWallet\n ? validateWithValidatedWallet()\n : await validateWithAddressFromInput();\n\n if (validatedBookmark) {\n const existingBookmark = getBookmark(validatedBookmark.address);\n if (existingBookmark) {\n setError({\n type: 'address',\n message: t('error.title.bookmarkAlreadyExists', {\n name: existingBookmark.name,\n }),\n });\n return;\n }\n\n (ref as MutableRefObject).current?.close();\n\n onAddBookmark({\n name: validatedBookmark.name,\n address: validatedBookmark.address,\n chainType: validatedBookmark.chainType,\n });\n }\n };\n\n const handleAddressInputChange = (e: ChangeEvent) => {\n if (error) {\n setError(undefined);\n }\n setAddress((e.target as HTMLInputElement).value.trim());\n };\n\n const handleNameInputChange = (e: ChangeEvent) => {\n if (error) {\n setError(undefined);\n }\n setName((e.target as HTMLInputElement).value);\n };\n\n const resetValues = () => {\n setName('');\n setAddress('');\n };\n\n return (\n \n \n \n \n \n {t('sendToWallet.bookmarkWallet')}\n {validatedWallet ? (\n \n {validatedWallet?.name ? (\n \n {validatedWallet?.name}\n \n ) : null}\n {validatedWallet?.address}\n \n ) : null}\n \n \n \n \n {!validatedWallet && (\n \n \n \n )}\n {error ? (\n }>{error.message}\n ) : null}\n \n \n {t('info.message.fundsToExchange')}\n \n }\n icon={}\n />\n \n \n \n {t('button.bookmark')}\n \n \n \n \n );\n});\n","import { Typography } from '@mui/material';\nimport type { PropsWithChildren, ReactNode } from 'react';\nimport { EmptyContainer, IconContainer } from './SendToWalletPage.style.js';\n\ninterface EmptyListIndicatorProps extends PropsWithChildren {\n icon: ReactNode;\n}\nexport const EmptyListIndicator = ({\n icon,\n children,\n}: EmptyListIndicatorProps) => (\n \n {icon}\n \n {children}\n \n \n);\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2m0 15-5-2.18L7 18V5h10z\"\n}), 'TurnedInNot');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9m-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8z\"\n}), 'History');","import { Box, ButtonBase, Typography, styled } from '@mui/material';\n\nexport const CardRowButton = styled(ButtonBase)(({ theme }) => ({\n background: 'none',\n color: 'inherit',\n border: 'none',\n font: 'inherit',\n cursor: 'pointer',\n outline: 'inherit',\n display: 'flex',\n width: '100%',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: theme.spacing(2),\n borderRadius: theme.shape.borderRadius,\n}));\n\nexport const CardRowContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n width: '100%',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: theme.spacing(2),\n}));\n\nexport const CardValue = styled(Typography)({\n lineHeight: '1.25',\n fontWeight: 500,\n});\n\nexport const CardTitleContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(1.5),\n}));\n","import type { MouseEventHandler, PropsWithChildren } from 'react';\nimport type { SettingCardTitle } from '../../pages/SettingsPage/SettingsCard/types.js';\nimport { Card } from './Card.js';\nimport {\n CardRowButton,\n CardTitleContainer,\n CardValue,\n} from './CardButton.style.js';\n\ninterface SettingCardButtonProps extends SettingCardTitle {\n onClick: MouseEventHandler;\n}\n\nexport const CardButton: React.FC<\n PropsWithChildren\n> = ({ onClick, icon, title, children }) => (\n \n \n \n {icon}\n {title}\n \n {children}\n \n \n);\n","import { Info, Wallet } from '@mui/icons-material';\nimport { Button, Typography } from '@mui/material';\nimport type { MutableRefObject } from 'react';\nimport { forwardRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { AlertMessage } from '../../components/AlertMessage/AlertMessage.js';\nimport { BottomSheet } from '../../components/BottomSheet/BottomSheet.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport type { Bookmark } from '../../stores/bookmarks/types.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport {\n IconContainer,\n SendToWalletButtonRow,\n SendToWalletSheetContainer,\n SheetAddressContainer,\n SheetTitle,\n} from './SendToWalletPage.style.js';\n\ninterface ConfirmAddressSheetProps {\n onConfirm: (wallet: Bookmark) => void;\n validatedBookmark?: Bookmark;\n}\n\nexport const ConfirmAddressSheet = forwardRef<\n BottomSheetBase,\n ConfirmAddressSheetProps\n>(({ validatedBookmark, onConfirm }, ref) => {\n const { t } = useTranslation();\n const { navigateBack } = useNavigateBack();\n const { setFieldValue } = useFieldActions();\n const { setSendToWallet } = useSendToWalletActions();\n\n const handleClose = () => {\n (ref as MutableRefObject).current?.close();\n };\n\n const handleConfirm = () => {\n if (validatedBookmark) {\n setFieldValue('toAddress', validatedBookmark.address, {\n isTouched: true,\n });\n onConfirm?.(validatedBookmark);\n setSendToWallet(true);\n handleClose();\n navigateBack();\n }\n };\n\n return (\n \n \n \n \n \n {t('sendToWallet.confirmWalletAddress')}\n \n {validatedBookmark?.name ? (\n \n {validatedBookmark?.name}\n \n ) : null}\n {validatedBookmark?.address}\n \n \n {t('info.message.fundsToExchange')}\n \n }\n icon={}\n />\n \n \n \n \n \n \n );\n});\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M18.21 9.21C15.93 10.78 13.45 13.3 13 17h2v2H9v-2h2c-.5-4.5-4.37-8-9-8V7c4.39 0 8.22 2.55 10 6.3 1.13-2.43 2.99-4.25 4.78-5.52L14 5h7v7z\"\n}), 'AirlineStops');","import { shallow } from 'zustand/shallow';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport {\n defaultConfigurableSettings,\n setDefaultSettings,\n useSettingsStore,\n} from '../stores/settings/useSettingsStore.js';\nimport { useTools } from './useTools.js';\n\nexport const useSettingMonitor = () => {\n const [\n disabledBridges,\n disabledExchanges,\n routePriority,\n slippage,\n gasPrice,\n ] = useSettingsStore(\n (state) => [\n state.disabledBridges,\n state.disabledExchanges,\n state.routePriority,\n state.slippage,\n state.gasPrice,\n ],\n shallow,\n );\n const { tools } = useTools();\n const resetSettings = useSettingsStore((state) => state.reset);\n const config = useWidgetConfig();\n\n const isSlippageChanged = config.slippage\n ? Number(slippage) !== config.slippage * 100\n : slippage !== defaultConfigurableSettings.slippage;\n\n const isSlippageOutsideRecommendedLimits =\n isSlippageChanged && Number(slippage) > 1;\n\n const isRoutePriorityChanged = config.routePriority\n ? routePriority !== config.routePriority\n : routePriority !== defaultConfigurableSettings.routePriority;\n\n const isGasPriceChanged = gasPrice !== defaultConfigurableSettings.gasPrice;\n\n const isBridgesChanged = Boolean(disabledBridges.length);\n const isExchangesChanged = Boolean(disabledExchanges.length);\n\n const isCustomRouteSettings =\n isBridgesChanged ||\n isExchangesChanged ||\n isSlippageChanged ||\n isRoutePriorityChanged ||\n isGasPriceChanged;\n\n const isRouteSettingsWithWarnings = isSlippageOutsideRecommendedLimits;\n\n const reset = () => {\n if (tools) {\n resetSettings(\n tools.bridges.map((tool) => tool.key),\n tools.exchanges.map((tool) => tool.key),\n );\n\n setDefaultSettings(config);\n }\n };\n\n return {\n isBridgesChanged,\n isExchangesChanged,\n isSlippageChanged,\n isSlippageOutsideRecommendedLimits,\n isRoutePriorityChanged,\n isGasPriceChanged,\n isCustomRouteSettings,\n isRouteSettingsWithWarnings,\n reset,\n };\n};\n","import { Box, Badge as MuiBadge, badgeClasses, styled } from '@mui/material';\n\nexport const SettingsList = styled(Box)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n gap: theme.spacing(1),\n}));\n\nexport const Badge = styled(MuiBadge)(({ theme }) => ({\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(1.25),\n [`.${badgeClasses.badge}`]: {\n width: 10,\n height: 10,\n // the following removes MUI styling so we can position the badge with flex\n position: 'relative',\n transform: 'translateX(0)',\n borderRadius: '50%',\n },\n}));\n","import type { BadgeProps } from '@mui/material';\nimport type { PropsWithChildren } from 'react';\nimport { CardValue } from '../../../components/Card/CardButton.style.js';\nimport { Badge } from './SettingCard.style.js';\n\ninterface BadgedValueProps {\n showBadge: boolean;\n badgeColor?: BadgeProps['color'];\n}\n\nexport const BadgedValue: React.FC> = ({\n showBadge,\n badgeColor,\n children,\n}) =>\n showBadge && badgeColor ? (\n \n {children}\n \n ) : (\n {children}\n );\n","import { AirlineStops, SwapHoriz } from '@mui/icons-material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { shallow } from 'zustand/shallow';\nimport { CardButton } from '../../components/Card/CardButton.js';\nimport { useSettingMonitor } from '../../hooks/useSettingMonitor.js';\nimport { useSettingsStore } from '../../stores/settings/useSettingsStore.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { BadgedValue } from './SettingsCard/BadgedValue.js';\n\nconst supportedIcons = {\n Bridges: AirlineStops,\n Exchanges: SwapHoriz,\n};\n\nexport const BridgeAndExchangeSettings: React.FC<{\n type: 'Bridges' | 'Exchanges';\n}> = ({ type }) => {\n const { isBridgesChanged, isExchangesChanged } = useSettingMonitor();\n const { t } = useTranslation();\n const navigate = useNavigate();\n const [enabledTools, tools] = useSettingsStore((state) => {\n const enabledTools = Object.values(state[`_enabled${type}`]);\n return [enabledTools.filter(Boolean).length, enabledTools.length];\n }, shallow);\n\n const customisationLookUp = {\n Bridges: isBridgesChanged,\n Exchanges: isExchangesChanged,\n };\n\n const handleClick = () => {\n navigate(navigationRoutes[type.toLowerCase() as 'bridges' | 'exchanges']);\n };\n\n const Icon = supportedIcons[type];\n\n return (\n }\n title={t(`settings.enabled${type}`)}\n >\n {`${enabledTools}/${tools}`}\n \n );\n};\n","// Source from https://github.com/alitaheri/normalize-scroll-left\nlet cachedType;\n\n/**\n * Based on the jquery plugin https://github.com/othree/jquery.rtl-scroll-type\n *\n * Types of scrollLeft, assuming scrollWidth=100 and direction is rtl.\n *\n * Type | <- Most Left | Most Right -> | Initial\n * ---------------- | ------------ | ------------- | -------\n * default | 0 | 100 | 100\n * negative (spec*) | -100 | 0 | 0\n * reverse | 100 | 0 | 0\n *\n * Edge 85: default\n * Safari 14: negative\n * Chrome 85: negative\n * Firefox 81: negative\n * IE11: reverse\n *\n * spec* https://drafts.csswg.org/cssom-view/#dom-window-scroll\n */\nexport function detectScrollType() {\n if (cachedType) {\n return cachedType;\n }\n const dummy = document.createElement('div');\n const container = document.createElement('div');\n container.style.width = '10px';\n container.style.height = '1px';\n dummy.appendChild(container);\n dummy.dir = 'rtl';\n dummy.style.fontSize = '14px';\n dummy.style.width = '4px';\n dummy.style.height = '1px';\n dummy.style.position = 'absolute';\n dummy.style.top = '-1000px';\n dummy.style.overflow = 'scroll';\n document.body.appendChild(dummy);\n cachedType = 'reverse';\n if (dummy.scrollLeft > 0) {\n cachedType = 'default';\n } else {\n dummy.scrollLeft = 1;\n if (dummy.scrollLeft === 0) {\n cachedType = 'negative';\n }\n }\n document.body.removeChild(dummy);\n return cachedType;\n}\n\n// Based on https://stackoverflow.com/a/24394376\nexport function getNormalizedScrollLeft(element, direction) {\n const scrollLeft = element.scrollLeft;\n\n // Perform the calculations only when direction is rtl to avoid messing up the ltr behavior\n if (direction !== 'rtl') {\n return scrollLeft;\n }\n const type = detectScrollType();\n switch (type) {\n case 'negative':\n return element.scrollWidth - element.clientWidth + scrollLeft;\n case 'reverse':\n return element.scrollWidth - element.clientWidth - scrollLeft;\n default:\n return scrollLeft;\n }\n}","function easeInOutSin(time) {\n return (1 + Math.sin(Math.PI * time - Math.PI / 2)) / 2;\n}\nexport default function animate(property, element, to, options = {}, cb = () => {}) {\n const {\n ease = easeInOutSin,\n duration = 300 // standard\n } = options;\n let start = null;\n const from = element[property];\n let cancelled = false;\n const cancel = () => {\n cancelled = true;\n };\n const step = timestamp => {\n if (cancelled) {\n cb(new Error('Animation cancelled'));\n return;\n }\n if (start === null) {\n start = timestamp;\n }\n const time = Math.min(1, (timestamp - start) / duration);\n element[property] = ease(time) * (to - from) + from;\n if (time >= 1) {\n requestAnimationFrame(() => {\n cb(null);\n });\n return;\n }\n requestAnimationFrame(step);\n };\n if (from === to) {\n cb(new Error('Element already at target position'));\n return cancel;\n }\n requestAnimationFrame(step);\n return cancel;\n}","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"onChange\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport debounce from '../utils/debounce';\nimport { ownerWindow, unstable_useEnhancedEffect as useEnhancedEffect } from '../utils';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst styles = {\n width: 99,\n height: 99,\n position: 'absolute',\n top: -9999,\n overflow: 'scroll'\n};\n\n/**\n * @ignore - internal component.\n * The component originates from https://github.com/STORIS/react-scrollbar-size.\n * It has been moved into the core in order to minimize the bundle size.\n */\nexport default function ScrollbarSize(props) {\n const {\n onChange\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const scrollbarHeight = React.useRef();\n const nodeRef = React.useRef(null);\n const setMeasurements = () => {\n scrollbarHeight.current = nodeRef.current.offsetHeight - nodeRef.current.clientHeight;\n };\n useEnhancedEffect(() => {\n const handleResize = debounce(() => {\n const prevHeight = scrollbarHeight.current;\n setMeasurements();\n if (prevHeight !== scrollbarHeight.current) {\n onChange(scrollbarHeight.current);\n }\n });\n const containerWindow = ownerWindow(nodeRef.current);\n containerWindow.addEventListener('resize', handleResize);\n return () => {\n handleResize.clear();\n containerWindow.removeEventListener('resize', handleResize);\n };\n }, [onChange]);\n React.useEffect(() => {\n setMeasurements();\n onChange(scrollbarHeight.current);\n }, [onChange]);\n return /*#__PURE__*/_jsx(\"div\", _extends({\n style: styles,\n ref: nodeRef\n }, other));\n}\nprocess.env.NODE_ENV !== \"production\" ? ScrollbarSize.propTypes = {\n onChange: PropTypes.func.isRequired\n} : void 0;","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z\"\n}), 'KeyboardArrowLeft');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z\"\n}), 'KeyboardArrowRight');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getTabScrollButtonUtilityClass(slot) {\n return generateUtilityClass('MuiTabScrollButton', slot);\n}\nconst tabScrollButtonClasses = generateUtilityClasses('MuiTabScrollButton', ['root', 'vertical', 'horizontal', 'disabled']);\nexport default tabScrollButtonClasses;","'use client';\n\n/* eslint-disable jsx-a11y/aria-role */\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\", \"slots\", \"slotProps\", \"direction\", \"orientation\", \"disabled\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { useRtl } from '@mui/system/RtlProvider';\nimport useSlotProps from '@mui/utils/useSlotProps';\nimport KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';\nimport KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';\nimport ButtonBase from '../ButtonBase';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport tabScrollButtonClasses, { getTabScrollButtonUtilityClass } from './tabScrollButtonClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n orientation,\n disabled\n } = ownerState;\n const slots = {\n root: ['root', orientation, disabled && 'disabled']\n };\n return composeClasses(slots, getTabScrollButtonUtilityClass, classes);\n};\nconst TabScrollButtonRoot = styled(ButtonBase, {\n name: 'MuiTabScrollButton',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.orientation && styles[ownerState.orientation]];\n }\n})(({\n ownerState\n}) => _extends({\n width: 40,\n flexShrink: 0,\n opacity: 0.8,\n [`&.${tabScrollButtonClasses.disabled}`]: {\n opacity: 0\n }\n}, ownerState.orientation === 'vertical' && {\n width: '100%',\n height: 40,\n '& svg': {\n transform: `rotate(${ownerState.isRtl ? -90 : 90}deg)`\n }\n}));\nconst TabScrollButton = /*#__PURE__*/React.forwardRef(function TabScrollButton(inProps, ref) {\n var _slots$StartScrollBut, _slots$EndScrollButto;\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiTabScrollButton'\n });\n const {\n className,\n slots = {},\n slotProps = {},\n direction\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const isRtl = useRtl();\n const ownerState = _extends({\n isRtl\n }, props);\n const classes = useUtilityClasses(ownerState);\n const StartButtonIcon = (_slots$StartScrollBut = slots.StartScrollButtonIcon) != null ? _slots$StartScrollBut : KeyboardArrowLeft;\n const EndButtonIcon = (_slots$EndScrollButto = slots.EndScrollButtonIcon) != null ? _slots$EndScrollButto : KeyboardArrowRight;\n const startButtonIconProps = useSlotProps({\n elementType: StartButtonIcon,\n externalSlotProps: slotProps.startScrollButtonIcon,\n additionalProps: {\n fontSize: 'small'\n },\n ownerState\n });\n const endButtonIconProps = useSlotProps({\n elementType: EndButtonIcon,\n externalSlotProps: slotProps.endScrollButtonIcon,\n additionalProps: {\n fontSize: 'small'\n },\n ownerState\n });\n return /*#__PURE__*/_jsx(TabScrollButtonRoot, _extends({\n component: \"div\",\n className: clsx(classes.root, className),\n ref: ref,\n role: null,\n ownerState: ownerState,\n tabIndex: null\n }, other, {\n children: direction === 'left' ? /*#__PURE__*/_jsx(StartButtonIcon, _extends({}, startButtonIconProps)) : /*#__PURE__*/_jsx(EndButtonIcon, _extends({}, endButtonIconProps))\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? TabScrollButton.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The direction the button should indicate.\n */\n direction: PropTypes.oneOf(['left', 'right']).isRequired,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * The component orientation (layout flow direction).\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired,\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n * @default {}\n */\n slotProps: PropTypes.shape({\n endScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n startScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n EndScrollButtonIcon: PropTypes.elementType,\n StartScrollButtonIcon: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default TabScrollButton;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getTabsUtilityClass(slot) {\n return generateUtilityClass('MuiTabs', slot);\n}\nconst tabsClasses = generateUtilityClasses('MuiTabs', ['root', 'vertical', 'flexContainer', 'flexContainerVertical', 'centered', 'scroller', 'fixed', 'scrollableX', 'scrollableY', 'hideScrollbar', 'scrollButtons', 'scrollButtonsHideMobile', 'indicator']);\nexport default tabsClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"aria-label\", \"aria-labelledby\", \"action\", \"centered\", \"children\", \"className\", \"component\", \"allowScrollButtonsMobile\", \"indicatorColor\", \"onChange\", \"orientation\", \"ScrollButtonComponent\", \"scrollButtons\", \"selectionFollowsFocus\", \"slots\", \"slotProps\", \"TabIndicatorProps\", \"TabScrollButtonProps\", \"textColor\", \"value\", \"variant\", \"visibleScrollbar\"];\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport refType from '@mui/utils/refType';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { useRtl } from '@mui/system/RtlProvider';\nimport useSlotProps from '@mui/utils/useSlotProps';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport useTheme from '../styles/useTheme';\nimport debounce from '../utils/debounce';\nimport { getNormalizedScrollLeft, detectScrollType } from '../utils/scrollLeft';\nimport animate from '../internal/animate';\nimport ScrollbarSize from './ScrollbarSize';\nimport TabScrollButton from '../TabScrollButton';\nimport useEventCallback from '../utils/useEventCallback';\nimport tabsClasses, { getTabsUtilityClass } from './tabsClasses';\nimport ownerDocument from '../utils/ownerDocument';\nimport ownerWindow from '../utils/ownerWindow';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst nextItem = (list, item) => {\n if (list === item) {\n return list.firstChild;\n }\n if (item && item.nextElementSibling) {\n return item.nextElementSibling;\n }\n return list.firstChild;\n};\nconst previousItem = (list, item) => {\n if (list === item) {\n return list.lastChild;\n }\n if (item && item.previousElementSibling) {\n return item.previousElementSibling;\n }\n return list.lastChild;\n};\nconst moveFocus = (list, currentFocus, traversalFunction) => {\n let wrappedOnce = false;\n let nextFocus = traversalFunction(list, currentFocus);\n while (nextFocus) {\n // Prevent infinite loop.\n if (nextFocus === list.firstChild) {\n if (wrappedOnce) {\n return;\n }\n wrappedOnce = true;\n }\n\n // Same logic as useAutocomplete.js\n const nextFocusDisabled = nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';\n if (!nextFocus.hasAttribute('tabindex') || nextFocusDisabled) {\n // Move to the next element.\n nextFocus = traversalFunction(list, nextFocus);\n } else {\n nextFocus.focus();\n return;\n }\n }\n};\nconst useUtilityClasses = ownerState => {\n const {\n vertical,\n fixed,\n hideScrollbar,\n scrollableX,\n scrollableY,\n centered,\n scrollButtonsHideMobile,\n classes\n } = ownerState;\n const slots = {\n root: ['root', vertical && 'vertical'],\n scroller: ['scroller', fixed && 'fixed', hideScrollbar && 'hideScrollbar', scrollableX && 'scrollableX', scrollableY && 'scrollableY'],\n flexContainer: ['flexContainer', vertical && 'flexContainerVertical', centered && 'centered'],\n indicator: ['indicator'],\n scrollButtons: ['scrollButtons', scrollButtonsHideMobile && 'scrollButtonsHideMobile'],\n scrollableX: [scrollableX && 'scrollableX'],\n hideScrollbar: [hideScrollbar && 'hideScrollbar']\n };\n return composeClasses(slots, getTabsUtilityClass, classes);\n};\nconst TabsRoot = styled('div', {\n name: 'MuiTabs',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [{\n [`& .${tabsClasses.scrollButtons}`]: styles.scrollButtons\n }, {\n [`& .${tabsClasses.scrollButtons}`]: ownerState.scrollButtonsHideMobile && styles.scrollButtonsHideMobile\n }, styles.root, ownerState.vertical && styles.vertical];\n }\n})(({\n ownerState,\n theme\n}) => _extends({\n overflow: 'hidden',\n minHeight: 48,\n // Add iOS momentum scrolling for iOS < 13.0\n WebkitOverflowScrolling: 'touch',\n display: 'flex'\n}, ownerState.vertical && {\n flexDirection: 'column'\n}, ownerState.scrollButtonsHideMobile && {\n [`& .${tabsClasses.scrollButtons}`]: {\n [theme.breakpoints.down('sm')]: {\n display: 'none'\n }\n }\n}));\nconst TabsScroller = styled('div', {\n name: 'MuiTabs',\n slot: 'Scroller',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.scroller, ownerState.fixed && styles.fixed, ownerState.hideScrollbar && styles.hideScrollbar, ownerState.scrollableX && styles.scrollableX, ownerState.scrollableY && styles.scrollableY];\n }\n})(({\n ownerState\n}) => _extends({\n position: 'relative',\n display: 'inline-block',\n flex: '1 1 auto',\n whiteSpace: 'nowrap'\n}, ownerState.fixed && {\n overflowX: 'hidden',\n width: '100%'\n}, ownerState.hideScrollbar && {\n // Hide dimensionless scrollbar on macOS\n scrollbarWidth: 'none',\n // Firefox\n '&::-webkit-scrollbar': {\n display: 'none' // Safari + Chrome\n }\n}, ownerState.scrollableX && {\n overflowX: 'auto',\n overflowY: 'hidden'\n}, ownerState.scrollableY && {\n overflowY: 'auto',\n overflowX: 'hidden'\n}));\nconst FlexContainer = styled('div', {\n name: 'MuiTabs',\n slot: 'FlexContainer',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.flexContainer, ownerState.vertical && styles.flexContainerVertical, ownerState.centered && styles.centered];\n }\n})(({\n ownerState\n}) => _extends({\n display: 'flex'\n}, ownerState.vertical && {\n flexDirection: 'column'\n}, ownerState.centered && {\n justifyContent: 'center'\n}));\nconst TabsIndicator = styled('span', {\n name: 'MuiTabs',\n slot: 'Indicator',\n overridesResolver: (props, styles) => styles.indicator\n})(({\n ownerState,\n theme\n}) => _extends({\n position: 'absolute',\n height: 2,\n bottom: 0,\n width: '100%',\n transition: theme.transitions.create()\n}, ownerState.indicatorColor === 'primary' && {\n backgroundColor: (theme.vars || theme).palette.primary.main\n}, ownerState.indicatorColor === 'secondary' && {\n backgroundColor: (theme.vars || theme).palette.secondary.main\n}, ownerState.vertical && {\n height: '100%',\n width: 2,\n right: 0\n}));\nconst TabsScrollbarSize = styled(ScrollbarSize)({\n overflowX: 'auto',\n overflowY: 'hidden',\n // Hide dimensionless scrollbar on macOS\n scrollbarWidth: 'none',\n // Firefox\n '&::-webkit-scrollbar': {\n display: 'none' // Safari + Chrome\n }\n});\nconst defaultIndicatorStyle = {};\nlet warnedOnceTabPresent = false;\nconst Tabs = /*#__PURE__*/React.forwardRef(function Tabs(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiTabs'\n });\n const theme = useTheme();\n const isRtl = useRtl();\n const {\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n action,\n centered = false,\n children: childrenProp,\n className,\n component = 'div',\n allowScrollButtonsMobile = false,\n indicatorColor = 'primary',\n onChange,\n orientation = 'horizontal',\n ScrollButtonComponent = TabScrollButton,\n scrollButtons = 'auto',\n selectionFollowsFocus,\n slots = {},\n slotProps = {},\n TabIndicatorProps = {},\n TabScrollButtonProps = {},\n textColor = 'primary',\n value,\n variant = 'standard',\n visibleScrollbar = false\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const scrollable = variant === 'scrollable';\n const vertical = orientation === 'vertical';\n const scrollStart = vertical ? 'scrollTop' : 'scrollLeft';\n const start = vertical ? 'top' : 'left';\n const end = vertical ? 'bottom' : 'right';\n const clientSize = vertical ? 'clientHeight' : 'clientWidth';\n const size = vertical ? 'height' : 'width';\n const ownerState = _extends({}, props, {\n component,\n allowScrollButtonsMobile,\n indicatorColor,\n orientation,\n vertical,\n scrollButtons,\n textColor,\n variant,\n visibleScrollbar,\n fixed: !scrollable,\n hideScrollbar: scrollable && !visibleScrollbar,\n scrollableX: scrollable && !vertical,\n scrollableY: scrollable && vertical,\n centered: centered && !scrollable,\n scrollButtonsHideMobile: !allowScrollButtonsMobile\n });\n const classes = useUtilityClasses(ownerState);\n const startScrollButtonIconProps = useSlotProps({\n elementType: slots.StartScrollButtonIcon,\n externalSlotProps: slotProps.startScrollButtonIcon,\n ownerState\n });\n const endScrollButtonIconProps = useSlotProps({\n elementType: slots.EndScrollButtonIcon,\n externalSlotProps: slotProps.endScrollButtonIcon,\n ownerState\n });\n if (process.env.NODE_ENV !== 'production') {\n if (centered && scrollable) {\n console.error('MUI: You can not use the `centered={true}` and `variant=\"scrollable\"` properties ' + 'at the same time on a `Tabs` component.');\n }\n }\n const [mounted, setMounted] = React.useState(false);\n const [indicatorStyle, setIndicatorStyle] = React.useState(defaultIndicatorStyle);\n const [displayStartScroll, setDisplayStartScroll] = React.useState(false);\n const [displayEndScroll, setDisplayEndScroll] = React.useState(false);\n const [updateScrollObserver, setUpdateScrollObserver] = React.useState(false);\n const [scrollerStyle, setScrollerStyle] = React.useState({\n overflow: 'hidden',\n scrollbarWidth: 0\n });\n const valueToIndex = new Map();\n const tabsRef = React.useRef(null);\n const tabListRef = React.useRef(null);\n const getTabsMeta = () => {\n const tabsNode = tabsRef.current;\n let tabsMeta;\n if (tabsNode) {\n const rect = tabsNode.getBoundingClientRect();\n // create a new object with ClientRect class props + scrollLeft\n tabsMeta = {\n clientWidth: tabsNode.clientWidth,\n scrollLeft: tabsNode.scrollLeft,\n scrollTop: tabsNode.scrollTop,\n scrollLeftNormalized: getNormalizedScrollLeft(tabsNode, isRtl ? 'rtl' : 'ltr'),\n scrollWidth: tabsNode.scrollWidth,\n top: rect.top,\n bottom: rect.bottom,\n left: rect.left,\n right: rect.right\n };\n }\n let tabMeta;\n if (tabsNode && value !== false) {\n const children = tabListRef.current.children;\n if (children.length > 0) {\n const tab = children[valueToIndex.get(value)];\n if (process.env.NODE_ENV !== 'production') {\n if (!tab) {\n console.error([`MUI: The \\`value\\` provided to the Tabs component is invalid.`, `None of the Tabs' children match with \"${value}\".`, valueToIndex.keys ? `You can provide one of the following values: ${Array.from(valueToIndex.keys()).join(', ')}.` : null].join('\\n'));\n }\n }\n tabMeta = tab ? tab.getBoundingClientRect() : null;\n if (process.env.NODE_ENV !== 'production') {\n if (process.env.NODE_ENV !== 'test' && !warnedOnceTabPresent && tabMeta && tabMeta.width === 0 && tabMeta.height === 0 &&\n // if the whole Tabs component is hidden, don't warn\n tabsMeta.clientWidth !== 0) {\n tabsMeta = null;\n console.error(['MUI: The `value` provided to the Tabs component is invalid.', `The Tab with this \\`value\\` (\"${value}\") is not part of the document layout.`, \"Make sure the tab item is present in the document or that it's not `display: none`.\"].join('\\n'));\n warnedOnceTabPresent = true;\n }\n }\n }\n }\n return {\n tabsMeta,\n tabMeta\n };\n };\n const updateIndicatorState = useEventCallback(() => {\n const {\n tabsMeta,\n tabMeta\n } = getTabsMeta();\n let startValue = 0;\n let startIndicator;\n if (vertical) {\n startIndicator = 'top';\n if (tabMeta && tabsMeta) {\n startValue = tabMeta.top - tabsMeta.top + tabsMeta.scrollTop;\n }\n } else {\n startIndicator = isRtl ? 'right' : 'left';\n if (tabMeta && tabsMeta) {\n const correction = isRtl ? tabsMeta.scrollLeftNormalized + tabsMeta.clientWidth - tabsMeta.scrollWidth : tabsMeta.scrollLeft;\n startValue = (isRtl ? -1 : 1) * (tabMeta[startIndicator] - tabsMeta[startIndicator] + correction);\n }\n }\n const newIndicatorStyle = {\n [startIndicator]: startValue,\n // May be wrong until the font is loaded.\n [size]: tabMeta ? tabMeta[size] : 0\n };\n\n // IE11 support, replace with Number.isNaN\n // eslint-disable-next-line no-restricted-globals\n if (isNaN(indicatorStyle[startIndicator]) || isNaN(indicatorStyle[size])) {\n setIndicatorStyle(newIndicatorStyle);\n } else {\n const dStart = Math.abs(indicatorStyle[startIndicator] - newIndicatorStyle[startIndicator]);\n const dSize = Math.abs(indicatorStyle[size] - newIndicatorStyle[size]);\n if (dStart >= 1 || dSize >= 1) {\n setIndicatorStyle(newIndicatorStyle);\n }\n }\n });\n const scroll = (scrollValue, {\n animation = true\n } = {}) => {\n if (animation) {\n animate(scrollStart, tabsRef.current, scrollValue, {\n duration: theme.transitions.duration.standard\n });\n } else {\n tabsRef.current[scrollStart] = scrollValue;\n }\n };\n const moveTabsScroll = delta => {\n let scrollValue = tabsRef.current[scrollStart];\n if (vertical) {\n scrollValue += delta;\n } else {\n scrollValue += delta * (isRtl ? -1 : 1);\n // Fix for Edge\n scrollValue *= isRtl && detectScrollType() === 'reverse' ? -1 : 1;\n }\n scroll(scrollValue);\n };\n const getScrollSize = () => {\n const containerSize = tabsRef.current[clientSize];\n let totalSize = 0;\n const children = Array.from(tabListRef.current.children);\n for (let i = 0; i < children.length; i += 1) {\n const tab = children[i];\n if (totalSize + tab[clientSize] > containerSize) {\n // If the first item is longer than the container size, then only scroll\n // by the container size.\n if (i === 0) {\n totalSize = containerSize;\n }\n break;\n }\n totalSize += tab[clientSize];\n }\n return totalSize;\n };\n const handleStartScrollClick = () => {\n moveTabsScroll(-1 * getScrollSize());\n };\n const handleEndScrollClick = () => {\n moveTabsScroll(getScrollSize());\n };\n\n // TODO Remove as browser support for hiding the scrollbar\n // with CSS improves.\n const handleScrollbarSizeChange = React.useCallback(scrollbarWidth => {\n setScrollerStyle({\n overflow: null,\n scrollbarWidth\n });\n }, []);\n const getConditionalElements = () => {\n const conditionalElements = {};\n conditionalElements.scrollbarSizeListener = scrollable ? /*#__PURE__*/_jsx(TabsScrollbarSize, {\n onChange: handleScrollbarSizeChange,\n className: clsx(classes.scrollableX, classes.hideScrollbar)\n }) : null;\n const scrollButtonsActive = displayStartScroll || displayEndScroll;\n const showScrollButtons = scrollable && (scrollButtons === 'auto' && scrollButtonsActive || scrollButtons === true);\n conditionalElements.scrollButtonStart = showScrollButtons ? /*#__PURE__*/_jsx(ScrollButtonComponent, _extends({\n slots: {\n StartScrollButtonIcon: slots.StartScrollButtonIcon\n },\n slotProps: {\n startScrollButtonIcon: startScrollButtonIconProps\n },\n orientation: orientation,\n direction: isRtl ? 'right' : 'left',\n onClick: handleStartScrollClick,\n disabled: !displayStartScroll\n }, TabScrollButtonProps, {\n className: clsx(classes.scrollButtons, TabScrollButtonProps.className)\n })) : null;\n conditionalElements.scrollButtonEnd = showScrollButtons ? /*#__PURE__*/_jsx(ScrollButtonComponent, _extends({\n slots: {\n EndScrollButtonIcon: slots.EndScrollButtonIcon\n },\n slotProps: {\n endScrollButtonIcon: endScrollButtonIconProps\n },\n orientation: orientation,\n direction: isRtl ? 'left' : 'right',\n onClick: handleEndScrollClick,\n disabled: !displayEndScroll\n }, TabScrollButtonProps, {\n className: clsx(classes.scrollButtons, TabScrollButtonProps.className)\n })) : null;\n return conditionalElements;\n };\n const scrollSelectedIntoView = useEventCallback(animation => {\n const {\n tabsMeta,\n tabMeta\n } = getTabsMeta();\n if (!tabMeta || !tabsMeta) {\n return;\n }\n if (tabMeta[start] < tabsMeta[start]) {\n // left side of button is out of view\n const nextScrollStart = tabsMeta[scrollStart] + (tabMeta[start] - tabsMeta[start]);\n scroll(nextScrollStart, {\n animation\n });\n } else if (tabMeta[end] > tabsMeta[end]) {\n // right side of button is out of view\n const nextScrollStart = tabsMeta[scrollStart] + (tabMeta[end] - tabsMeta[end]);\n scroll(nextScrollStart, {\n animation\n });\n }\n });\n const updateScrollButtonState = useEventCallback(() => {\n if (scrollable && scrollButtons !== false) {\n setUpdateScrollObserver(!updateScrollObserver);\n }\n });\n React.useEffect(() => {\n const handleResize = debounce(() => {\n // If the Tabs component is replaced by Suspense with a fallback, the last\n // ResizeObserver's handler that runs because of the change in the layout is trying to\n // access a dom node that is no longer there (as the fallback component is being shown instead).\n // See https://github.com/mui/material-ui/issues/33276\n // TODO: Add tests that will ensure the component is not failing when\n // replaced by Suspense with a fallback, once React is updated to version 18\n if (tabsRef.current) {\n updateIndicatorState();\n }\n });\n let resizeObserver;\n\n /**\n * @type {MutationCallback}\n */\n const handleMutation = records => {\n records.forEach(record => {\n record.removedNodes.forEach(item => {\n var _resizeObserver;\n (_resizeObserver = resizeObserver) == null || _resizeObserver.unobserve(item);\n });\n record.addedNodes.forEach(item => {\n var _resizeObserver2;\n (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.observe(item);\n });\n });\n handleResize();\n updateScrollButtonState();\n };\n const win = ownerWindow(tabsRef.current);\n win.addEventListener('resize', handleResize);\n let mutationObserver;\n if (typeof ResizeObserver !== 'undefined') {\n resizeObserver = new ResizeObserver(handleResize);\n Array.from(tabListRef.current.children).forEach(child => {\n resizeObserver.observe(child);\n });\n }\n if (typeof MutationObserver !== 'undefined') {\n mutationObserver = new MutationObserver(handleMutation);\n mutationObserver.observe(tabListRef.current, {\n childList: true\n });\n }\n return () => {\n var _mutationObserver, _resizeObserver3;\n handleResize.clear();\n win.removeEventListener('resize', handleResize);\n (_mutationObserver = mutationObserver) == null || _mutationObserver.disconnect();\n (_resizeObserver3 = resizeObserver) == null || _resizeObserver3.disconnect();\n };\n }, [updateIndicatorState, updateScrollButtonState]);\n\n /**\n * Toggle visibility of start and end scroll buttons\n * Using IntersectionObserver on first and last Tabs.\n */\n React.useEffect(() => {\n const tabListChildren = Array.from(tabListRef.current.children);\n const length = tabListChildren.length;\n if (typeof IntersectionObserver !== 'undefined' && length > 0 && scrollable && scrollButtons !== false) {\n const firstTab = tabListChildren[0];\n const lastTab = tabListChildren[length - 1];\n const observerOptions = {\n root: tabsRef.current,\n threshold: 0.99\n };\n const handleScrollButtonStart = entries => {\n setDisplayStartScroll(!entries[0].isIntersecting);\n };\n const firstObserver = new IntersectionObserver(handleScrollButtonStart, observerOptions);\n firstObserver.observe(firstTab);\n const handleScrollButtonEnd = entries => {\n setDisplayEndScroll(!entries[0].isIntersecting);\n };\n const lastObserver = new IntersectionObserver(handleScrollButtonEnd, observerOptions);\n lastObserver.observe(lastTab);\n return () => {\n firstObserver.disconnect();\n lastObserver.disconnect();\n };\n }\n return undefined;\n }, [scrollable, scrollButtons, updateScrollObserver, childrenProp == null ? void 0 : childrenProp.length]);\n React.useEffect(() => {\n setMounted(true);\n }, []);\n React.useEffect(() => {\n updateIndicatorState();\n });\n React.useEffect(() => {\n // Don't animate on the first render.\n scrollSelectedIntoView(defaultIndicatorStyle !== indicatorStyle);\n }, [scrollSelectedIntoView, indicatorStyle]);\n React.useImperativeHandle(action, () => ({\n updateIndicator: updateIndicatorState,\n updateScrollButtons: updateScrollButtonState\n }), [updateIndicatorState, updateScrollButtonState]);\n const indicator = /*#__PURE__*/_jsx(TabsIndicator, _extends({}, TabIndicatorProps, {\n className: clsx(classes.indicator, TabIndicatorProps.className),\n ownerState: ownerState,\n style: _extends({}, indicatorStyle, TabIndicatorProps.style)\n }));\n let childIndex = 0;\n const children = React.Children.map(childrenProp, child => {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return null;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"MUI: The Tabs component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n const childValue = child.props.value === undefined ? childIndex : child.props.value;\n valueToIndex.set(childValue, childIndex);\n const selected = childValue === value;\n childIndex += 1;\n return /*#__PURE__*/React.cloneElement(child, _extends({\n fullWidth: variant === 'fullWidth',\n indicator: selected && !mounted && indicator,\n selected,\n selectionFollowsFocus,\n onChange,\n textColor,\n value: childValue\n }, childIndex === 1 && value === false && !child.props.tabIndex ? {\n tabIndex: 0\n } : {}));\n });\n const handleKeyDown = event => {\n const list = tabListRef.current;\n const currentFocus = ownerDocument(list).activeElement;\n // Keyboard navigation assumes that [role=\"tab\"] are siblings\n // though we might warn in the future about nested, interactive elements\n // as a a11y violation\n const role = currentFocus.getAttribute('role');\n if (role !== 'tab') {\n return;\n }\n let previousItemKey = orientation === 'horizontal' ? 'ArrowLeft' : 'ArrowUp';\n let nextItemKey = orientation === 'horizontal' ? 'ArrowRight' : 'ArrowDown';\n if (orientation === 'horizontal' && isRtl) {\n // swap previousItemKey with nextItemKey\n previousItemKey = 'ArrowRight';\n nextItemKey = 'ArrowLeft';\n }\n switch (event.key) {\n case previousItemKey:\n event.preventDefault();\n moveFocus(list, currentFocus, previousItem);\n break;\n case nextItemKey:\n event.preventDefault();\n moveFocus(list, currentFocus, nextItem);\n break;\n case 'Home':\n event.preventDefault();\n moveFocus(list, null, nextItem);\n break;\n case 'End':\n event.preventDefault();\n moveFocus(list, null, previousItem);\n break;\n default:\n break;\n }\n };\n const conditionalElements = getConditionalElements();\n return /*#__PURE__*/_jsxs(TabsRoot, _extends({\n className: clsx(classes.root, className),\n ownerState: ownerState,\n ref: ref,\n as: component\n }, other, {\n children: [conditionalElements.scrollButtonStart, conditionalElements.scrollbarSizeListener, /*#__PURE__*/_jsxs(TabsScroller, {\n className: classes.scroller,\n ownerState: ownerState,\n style: {\n overflow: scrollerStyle.overflow,\n [vertical ? `margin${isRtl ? 'Left' : 'Right'}` : 'marginBottom']: visibleScrollbar ? undefined : -scrollerStyle.scrollbarWidth\n },\n ref: tabsRef,\n children: [/*#__PURE__*/_jsx(FlexContainer, {\n \"aria-label\": ariaLabel,\n \"aria-labelledby\": ariaLabelledBy,\n \"aria-orientation\": orientation === 'vertical' ? 'vertical' : null,\n className: classes.flexContainer,\n ownerState: ownerState,\n onKeyDown: handleKeyDown,\n ref: tabListRef,\n role: \"tablist\",\n children: children\n }), mounted && indicator]\n }), conditionalElements.scrollButtonEnd]\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Tabs.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Callback fired when the component mounts.\n * This is useful when you want to trigger an action programmatically.\n * It supports two actions: `updateIndicator()` and `updateScrollButtons()`\n *\n * @param {object} actions This object contains all possible actions\n * that can be triggered programmatically.\n */\n action: refType,\n /**\n * If `true`, the scroll buttons aren't forced hidden on mobile.\n * By default the scroll buttons are hidden on mobile and takes precedence over `scrollButtons`.\n * @default false\n */\n allowScrollButtonsMobile: PropTypes.bool,\n /**\n * The label for the Tabs as a string.\n */\n 'aria-label': PropTypes.string,\n /**\n * An id or list of ids separated by a space that label the Tabs.\n */\n 'aria-labelledby': PropTypes.string,\n /**\n * If `true`, the tabs are centered.\n * This prop is intended for large views.\n * @default false\n */\n centered: PropTypes.bool,\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * Determines the color of the indicator.\n * @default 'primary'\n */\n indicatorColor: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]),\n /**\n * Callback fired when the value changes.\n *\n * @param {React.SyntheticEvent} event The event source of the callback. **Warning**: This is a generic event not a change event.\n * @param {any} value We default to the index of the child (number)\n */\n onChange: PropTypes.func,\n /**\n * The component orientation (layout flow direction).\n * @default 'horizontal'\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']),\n /**\n * The component used to render the scroll buttons.\n * @default TabScrollButton\n */\n ScrollButtonComponent: PropTypes.elementType,\n /**\n * Determine behavior of scroll buttons when tabs are set to scroll:\n *\n * - `auto` will only present them when not all the items are visible.\n * - `true` will always present them.\n * - `false` will never present them.\n *\n * By default the scroll buttons are hidden on mobile.\n * This behavior can be disabled with `allowScrollButtonsMobile`.\n * @default 'auto'\n */\n scrollButtons: PropTypes /* @typescript-to-proptypes-ignore */.oneOf(['auto', false, true]),\n /**\n * If `true` the selected tab changes on focus. Otherwise it only\n * changes on activation.\n */\n selectionFollowsFocus: PropTypes.bool,\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n * @default {}\n */\n slotProps: PropTypes.shape({\n endScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n startScrollButtonIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n EndScrollButtonIcon: PropTypes.elementType,\n StartScrollButtonIcon: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * Props applied to the tab indicator element.\n * @default {}\n */\n TabIndicatorProps: PropTypes.object,\n /**\n * Props applied to the [`TabScrollButton`](/material-ui/api/tab-scroll-button/) element.\n * @default {}\n */\n TabScrollButtonProps: PropTypes.object,\n /**\n * Determines the color of the `Tab`.\n * @default 'primary'\n */\n textColor: PropTypes.oneOf(['inherit', 'primary', 'secondary']),\n /**\n * The value of the currently selected `Tab`.\n * If you don't want any selected `Tab`, you can set this prop to `false`.\n */\n value: PropTypes.any,\n /**\n * Determines additional display behavior of the tabs:\n *\n * - `scrollable` will invoke scrolling properties and allow for horizontally\n * scrolling (or swiping) of the tab bar.\n * - `fullWidth` will make the tabs grow to use all the available space,\n * which should be used for small views, like on mobile.\n * - `standard` will render the default state.\n * @default 'standard'\n */\n variant: PropTypes.oneOf(['fullWidth', 'scrollable', 'standard']),\n /**\n * If `true`, the scrollbar is visible. It can be useful when displaying\n * a long vertical list of tabs.\n * @default false\n */\n visibleScrollbar: PropTypes.bool\n} : void 0;\nexport default Tabs;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getTabUtilityClass(slot) {\n return generateUtilityClass('MuiTab', slot);\n}\nconst tabClasses = generateUtilityClasses('MuiTab', ['root', 'labelIcon', 'textColorInherit', 'textColorPrimary', 'textColorSecondary', 'selected', 'disabled', 'fullWidth', 'wrapped', 'iconWrapper']);\nexport default tabClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\", \"disabled\", \"disableFocusRipple\", \"fullWidth\", \"icon\", \"iconPosition\", \"indicator\", \"label\", \"onChange\", \"onClick\", \"onFocus\", \"selected\", \"selectionFollowsFocus\", \"textColor\", \"value\", \"wrapped\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport ButtonBase from '../ButtonBase';\nimport capitalize from '../utils/capitalize';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport unsupportedProp from '../utils/unsupportedProp';\nimport tabClasses, { getTabUtilityClass } from './tabClasses';\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n textColor,\n fullWidth,\n wrapped,\n icon,\n label,\n selected,\n disabled\n } = ownerState;\n const slots = {\n root: ['root', icon && label && 'labelIcon', `textColor${capitalize(textColor)}`, fullWidth && 'fullWidth', wrapped && 'wrapped', selected && 'selected', disabled && 'disabled'],\n iconWrapper: ['iconWrapper']\n };\n return composeClasses(slots, getTabUtilityClass, classes);\n};\nconst TabRoot = styled(ButtonBase, {\n name: 'MuiTab',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.label && ownerState.icon && styles.labelIcon, styles[`textColor${capitalize(ownerState.textColor)}`], ownerState.fullWidth && styles.fullWidth, ownerState.wrapped && styles.wrapped, {\n [`& .${tabClasses.iconWrapper}`]: styles.iconWrapper\n }];\n }\n})(({\n theme,\n ownerState\n}) => _extends({}, theme.typography.button, {\n maxWidth: 360,\n minWidth: 90,\n position: 'relative',\n minHeight: 48,\n flexShrink: 0,\n padding: '12px 16px',\n overflow: 'hidden',\n whiteSpace: 'normal',\n textAlign: 'center'\n}, ownerState.label && {\n flexDirection: ownerState.iconPosition === 'top' || ownerState.iconPosition === 'bottom' ? 'column' : 'row'\n}, {\n lineHeight: 1.25\n}, ownerState.icon && ownerState.label && {\n minHeight: 72,\n paddingTop: 9,\n paddingBottom: 9,\n [`& > .${tabClasses.iconWrapper}`]: _extends({}, ownerState.iconPosition === 'top' && {\n marginBottom: 6\n }, ownerState.iconPosition === 'bottom' && {\n marginTop: 6\n }, ownerState.iconPosition === 'start' && {\n marginRight: theme.spacing(1)\n }, ownerState.iconPosition === 'end' && {\n marginLeft: theme.spacing(1)\n })\n}, ownerState.textColor === 'inherit' && {\n color: 'inherit',\n opacity: 0.6,\n // same opacity as theme.palette.text.secondary\n [`&.${tabClasses.selected}`]: {\n opacity: 1\n },\n [`&.${tabClasses.disabled}`]: {\n opacity: (theme.vars || theme).palette.action.disabledOpacity\n }\n}, ownerState.textColor === 'primary' && {\n color: (theme.vars || theme).palette.text.secondary,\n [`&.${tabClasses.selected}`]: {\n color: (theme.vars || theme).palette.primary.main\n },\n [`&.${tabClasses.disabled}`]: {\n color: (theme.vars || theme).palette.text.disabled\n }\n}, ownerState.textColor === 'secondary' && {\n color: (theme.vars || theme).palette.text.secondary,\n [`&.${tabClasses.selected}`]: {\n color: (theme.vars || theme).palette.secondary.main\n },\n [`&.${tabClasses.disabled}`]: {\n color: (theme.vars || theme).palette.text.disabled\n }\n}, ownerState.fullWidth && {\n flexShrink: 1,\n flexGrow: 1,\n flexBasis: 0,\n maxWidth: 'none'\n}, ownerState.wrapped && {\n fontSize: theme.typography.pxToRem(12)\n}));\nconst Tab = /*#__PURE__*/React.forwardRef(function Tab(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiTab'\n });\n const {\n className,\n disabled = false,\n disableFocusRipple = false,\n // eslint-disable-next-line react/prop-types\n fullWidth,\n icon: iconProp,\n iconPosition = 'top',\n // eslint-disable-next-line react/prop-types\n indicator,\n label,\n onChange,\n onClick,\n onFocus,\n // eslint-disable-next-line react/prop-types\n selected,\n // eslint-disable-next-line react/prop-types\n selectionFollowsFocus,\n // eslint-disable-next-line react/prop-types\n textColor = 'inherit',\n value,\n wrapped = false\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n disabled,\n disableFocusRipple,\n selected,\n icon: !!iconProp,\n iconPosition,\n label: !!label,\n fullWidth,\n textColor,\n wrapped\n });\n const classes = useUtilityClasses(ownerState);\n const icon = iconProp && label && /*#__PURE__*/React.isValidElement(iconProp) ? /*#__PURE__*/React.cloneElement(iconProp, {\n className: clsx(classes.iconWrapper, iconProp.props.className)\n }) : iconProp;\n const handleClick = event => {\n if (!selected && onChange) {\n onChange(event, value);\n }\n if (onClick) {\n onClick(event);\n }\n };\n const handleFocus = event => {\n if (selectionFollowsFocus && !selected && onChange) {\n onChange(event, value);\n }\n if (onFocus) {\n onFocus(event);\n }\n };\n return /*#__PURE__*/_jsxs(TabRoot, _extends({\n focusRipple: !disableFocusRipple,\n className: clsx(classes.root, className),\n ref: ref,\n role: \"tab\",\n \"aria-selected\": selected,\n disabled: disabled,\n onClick: handleClick,\n onFocus: handleFocus,\n ownerState: ownerState,\n tabIndex: selected ? 0 : -1\n }, other, {\n children: [iconPosition === 'top' || iconPosition === 'start' ? /*#__PURE__*/_jsxs(React.Fragment, {\n children: [icon, label]\n }) : /*#__PURE__*/_jsxs(React.Fragment, {\n children: [label, icon]\n }), indicator]\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Tab.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * This prop isn't supported.\n * Use the `component` prop if you need to change the children structure.\n */\n children: unsupportedProp,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the keyboard focus ripple is disabled.\n * @default false\n */\n disableFocusRipple: PropTypes.bool,\n /**\n * If `true`, the ripple effect is disabled.\n *\n * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure\n * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.\n * @default false\n */\n disableRipple: PropTypes.bool,\n /**\n * The icon to display.\n */\n icon: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),\n /**\n * The position of the icon relative to the label.\n * @default 'top'\n */\n iconPosition: PropTypes.oneOf(['bottom', 'end', 'start', 'top']),\n /**\n * The label element.\n */\n label: PropTypes.node,\n /**\n * @ignore\n */\n onChange: PropTypes.func,\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * You can provide your own value. Otherwise, we fallback to the child position index.\n */\n value: PropTypes.any,\n /**\n * Tab labels appear in a single row.\n * They can use a second line if needed.\n * @default false\n */\n wrapped: PropTypes.bool\n} : void 0;\nexport default Tab;","import type { TabProps } from '@mui/material';\nimport {\n Tab as MuiTab,\n Tabs as MuiTabs,\n alpha,\n styled,\n tabClasses,\n tabsClasses,\n} from '@mui/material';\n\nexport const Tabs = styled(MuiTabs)(({ theme }) => ({\n flex: 1,\n [`.${tabsClasses.indicator}`]: {\n top: theme.spacing(0.5),\n left: theme.spacing(0.5),\n height: `calc(100% - ${theme.spacing(1)})`,\n width: `calc(100% - ${theme.spacing(1)})`,\n },\n [`.${tabsClasses.fixed}`]: {\n padding: theme.spacing(0.5),\n },\n}));\n\nexport const CardTabs = styled(Tabs)(({ theme }) => ({\n backgroundColor:\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, 0.04)\n : alpha(theme.palette.common.white, 0.08),\n [`.${tabsClasses.indicator}`]: {\n backgroundColor:\n theme.palette.mode === 'light'\n ? theme.palette.background.paper\n : alpha(theme.palette.common.black, 0.56),\n },\n}));\n\nexport const Tab = styled(MuiTab)(({ theme }) => ({\n zIndex: 1,\n flex: 1,\n textTransform: 'none',\n fontSize: '1rem',\n fontWeight: 700,\n color:\n theme.palette.mode === 'light'\n ? theme.palette.common.black\n : theme.palette.common.white,\n [`&.${tabClasses.selected}`]: {\n color:\n theme.palette.mode === 'light'\n ? theme.palette.common.black\n : theme.palette.common.white,\n },\n}));\n","import type { PropsWithChildren } from 'react';\nimport { createContext, useContext, useEffect, useId, useState } from 'react';\n\nconst SettingsAccordionContext = createContext({\n setOpenCard: (id: string) => {},\n openCard: '',\n});\n\nexport const SettingsCardAccordion: React.FC = ({\n children,\n}) => {\n const [openCard, setOpenCard] = useState('');\n\n return (\n \n {children}\n \n );\n};\n\nexport const useSettingsCardExpandable = () => {\n const settingCardExpandableId = useId();\n const [expanded, setExpanded] = useState(false);\n const { openCard, setOpenCard } = useContext(SettingsAccordionContext);\n const toggleExpanded = () => {\n const newExpanded = !expanded;\n setExpanded(newExpanded);\n\n if (newExpanded && openCard !== settingCardExpandableId) {\n setOpenCard(settingCardExpandableId);\n }\n };\n\n useEffect(() => {\n if (openCard !== settingCardExpandableId) {\n setExpanded(false);\n }\n }, [settingCardExpandableId, openCard]);\n\n return {\n expanded,\n toggleExpanded,\n };\n};\n","import { Collapse } from '@mui/material';\nimport type { PropsWithChildren, ReactNode } from 'react';\nimport { useId } from 'react';\nimport { Card } from '../../../components/Card/Card.js';\nimport {\n CardRowButton,\n CardTitleContainer,\n CardValue,\n} from '../../../components/Card/CardButton.style.js';\nimport { useSettingsCardExpandable } from './SettingsAccordian.js';\nimport type { SettingCardTitle } from './types.js';\n\ninterface SettingCardExpandableProps extends SettingCardTitle {\n value: ReactNode;\n}\n\nexport const SettingCardExpandable: React.FC<\n PropsWithChildren\n> = ({ icon, title, value, children }) => {\n const { expanded, toggleExpanded } = useSettingsCardExpandable();\n const buttonId = useId();\n const collapseId = useId();\n\n return (\n \n \n \n {icon}\n {title}\n \n {!expanded && value}\n \n \n {children}\n \n \n );\n};\n","import { EvStation } from '@mui/icons-material';\nimport { useTranslation } from 'react-i18next';\nimport { CardTabs, Tab } from '../../components/Tabs/Tabs.style.js';\nimport { useSettingMonitor } from '../../hooks/useSettingMonitor.js';\nimport { useSettings } from '../../stores/settings/useSettings.js';\nimport { useSettingsStore } from '../../stores/settings/useSettingsStore.js';\nimport { BadgedValue } from './SettingsCard/BadgedValue.js';\nimport { SettingCardExpandable } from './SettingsCard/SettingCardExpandable.js';\n\nexport const GasPriceSettings: React.FC = () => {\n const { t } = useTranslation();\n const setValue = useSettingsStore((state) => state.setValue);\n const { isGasPriceChanged } = useSettingMonitor();\n const { gasPrice } = useSettings(['gasPrice']);\n\n const handleGasPriceChange = (_: React.SyntheticEvent, gasPrice: string) => {\n setValue('gasPrice', gasPrice);\n };\n\n return (\n \n {t(`settings.gasPrice.${gasPrice}` as any)}\n \n }\n icon={}\n title={t(`settings.gasPrice.title`)}\n >\n \n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2m6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56M12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96M4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56m2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8M12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96M14.34 14H9.66c-.09-.66-.16-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2m.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56M16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2z\"\n}), 'Language');","import { Language } from '@mui/icons-material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { CardButton } from '../../components/Card/CardButton.js';\nimport { CardValue } from '../../components/Card/CardButton.style.js';\nimport { useLanguages } from '../../hooks/useLanguages.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\n\nexport const LanguageSetting: React.FC = () => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { hiddenUI } = useWidgetConfig();\n const { selectedLanguageDisplayName } = useLanguages();\n\n if (hiddenUI?.includes(HiddenUI.Language)) {\n return null;\n }\n\n const handleClick = () => {\n navigate(navigationRoutes.languages);\n };\n\n return (\n }\n title={t(`language.title`)}\n >\n {selectedLanguageDisplayName}\n \n );\n};\n","import { Box, styled } from '@mui/material';\nimport { getContrastAlphaColor } from '../../utils/colors.js';\n\nexport const ResetButtonContainer = styled(Box)(({ theme }) => ({\n background: getContrastAlphaColor(theme, 0.04),\n borderRadius: '16px',\n padding: '16px',\n\n [`svg`]: {\n fill: getContrastAlphaColor(theme, 0.4),\n },\n}));\n","import { InfoRounded } from '@mui/icons-material';\nimport {\n Box,\n Button,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n} from '@mui/material';\nimport { useCallback, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { Dialog } from '../../components/Dialog.js';\nimport { useSettingMonitor } from '../../hooks/useSettingMonitor.js';\nimport { ResetButtonContainer } from './ResetSettingsButton.style.js';\n\nexport const ResetSettingsButton: React.FC = () => {\n const { t } = useTranslation();\n const { isCustomRouteSettings, reset } = useSettingMonitor();\n const [open, setOpen] = useState(false);\n\n const toggleDialog = useCallback(() => {\n setOpen((open) => !open);\n }, []);\n\n const handleReset = () => {\n reset();\n toggleDialog();\n };\n\n if (!isCustomRouteSettings) {\n return null;\n }\n\n return (\n \n \n \n \n {t(`settings.resetSettings`)}\n \n \n\n \n {t('warning.title.resetSettings')}\n \n \n {t('warning.message.resetSettings')}\n \n \n \n \n \n \n \n \n \n );\n};\n","import type { Order } from '@lifi/sdk';\nimport { Route } from '@mui/icons-material';\nimport { useTranslation } from 'react-i18next';\nimport { CardTabs, Tab } from '../../components/Tabs/Tabs.style.js';\nimport { useSettingMonitor } from '../../hooks/useSettingMonitor.js';\nimport { useSettings } from '../../stores/settings/useSettings.js';\nimport { useSettingsStore } from '../../stores/settings/useSettingsStore.js';\nimport { BadgedValue } from './SettingsCard/BadgedValue.js';\nimport { SettingCardExpandable } from './SettingsCard/SettingCardExpandable.js';\n\nconst Priorities: Order[] = ['CHEAPEST', 'FASTEST'];\n\nexport const RoutePrioritySettings: React.FC = () => {\n const { t } = useTranslation();\n const setValue = useSettingsStore((state) => state.setValue);\n const { isRoutePriorityChanged } = useSettingMonitor();\n const { routePriority } = useSettings(['routePriority']);\n const currentRoutePriority = routePriority ?? '';\n\n const handleRoutePriorityChange = (\n _: React.SyntheticEvent,\n routePriority: Order,\n ) => {\n setValue('routePriority', routePriority);\n };\n\n return (\n \n {t(`main.tags.${currentRoutePriority.toLowerCase()}` as any)}\n \n }\n icon={}\n title={t(`settings.routePriority`)}\n >\n \n {Priorities.map((priority) => {\n return (\n \n );\n })}\n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M7.5 11C9.43 11 11 9.43 11 7.5S9.43 4 7.5 4 4 5.57 4 7.5 5.57 11 7.5 11m0-5C8.33 6 9 6.67 9 7.5S8.33 9 7.5 9 6 8.33 6 7.5 6.67 6 7.5 6M4.0025 18.5832 18.59 3.9955l1.4142 1.4143L5.4167 19.9974zM16.5 13c-1.93 0-3.5 1.57-3.5 3.5s1.57 3.5 3.5 3.5 3.5-1.57 3.5-3.5-1.57-3.5-3.5-3.5m0 5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5\"\n}), 'Percent');","import type { Theme } from '@mui/material';\nimport {\n Box,\n ButtonBase,\n InputBase,\n alpha,\n inputBaseClasses,\n styled,\n} from '@mui/material';\n\nexport const SettingsFieldSet = styled(Box)(({ theme }) => ({\n display: 'flex',\n backgroundColor:\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, 0.04)\n : alpha(theme.palette.common.white, 0.08),\n borderRadius: theme.shape.borderRadius,\n padding: theme.spacing(0.5),\n gap: theme.spacing(0.5),\n height: '3.5rem',\n}));\n\nconst slippageControlSelected = (theme: Theme) => ({\n backgroundColor:\n theme.palette.mode === 'light'\n ? theme.palette.background.paper\n : alpha(theme.palette.common.black, 0.56),\n borderRadius: theme.shape.borderRadius - 4,\n boxShadow: `0px 2px 4px ${alpha(theme.palette.common.black, 0.04)}`,\n});\n\ninterface SlippageDefaultProps {\n selected?: boolean;\n}\n\nexport const SlippageDefaultButton = styled(ButtonBase)(({\n theme,\n selected,\n}) => {\n const selectedStyle = selected\n ? {\n '&:not(:focus)': {\n ...slippageControlSelected(theme),\n },\n }\n : {};\n\n return {\n height: '100%',\n width: '100%',\n fontSize: '1rem',\n fontWeight: 700,\n '&:focus': {\n ...slippageControlSelected(theme),\n },\n ...selectedStyle,\n };\n});\n\nexport const SlippageCustomInput = styled(InputBase)(({\n theme,\n selected,\n}) => {\n const selectedStyle = selected\n ? {\n '&:not(:focus)': {\n ...slippageControlSelected(theme),\n },\n }\n : {};\n\n return {\n height: '100%',\n width: '100%',\n\n [`.${inputBaseClasses.input}`]: {\n height: '100%',\n width: '100%',\n padding: 0,\n textAlign: 'center',\n '&::placeholder': {\n fontSize: '1rem',\n fontWeight: 700,\n opacity: 1,\n },\n '&:focus': {\n ...slippageControlSelected(theme),\n },\n ...selectedStyle,\n },\n };\n});\n\nexport const SlippageLimitsWarningContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n gap: theme.spacing(1.25),\n marginTop: theme.spacing(1.5),\n}));\n","import { Percent, WarningRounded } from '@mui/icons-material';\nimport { Box, Typography } from '@mui/material';\nimport type { ChangeEventHandler, FocusEventHandler } from 'react';\nimport { useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useSettingMonitor } from '../../../hooks/useSettingMonitor.js';\nimport { useSettings } from '../../../stores/settings/useSettings.js';\nimport {\n defaultSlippage,\n useSettingsStore,\n} from '../../../stores/settings/useSettingsStore.js';\nimport { formatSlippage } from '../../../utils/format.js';\nimport { BadgedValue } from '../SettingsCard/BadgedValue.js';\nimport { SettingCardExpandable } from '../SettingsCard/SettingCardExpandable.js';\nimport {\n SettingsFieldSet,\n SlippageCustomInput,\n SlippageDefaultButton,\n SlippageLimitsWarningContainer,\n} from './SlippageSettings.style.js';\n\nexport const SlippageSettings: React.FC = () => {\n const { t } = useTranslation();\n const { isSlippageOutsideRecommendedLimits, isSlippageChanged } =\n useSettingMonitor();\n const { slippage } = useSettings(['slippage']);\n const setValue = useSettingsStore((state) => state.setValue);\n const defaultValue = useRef(slippage);\n const [focused, setFocused] = useState<'input' | 'button'>();\n\n const handleDefaultClick = () => {\n setValue('slippage', formatSlippage(defaultSlippage, defaultValue.current));\n };\n\n const handleInputUpdate: ChangeEventHandler = (event) => {\n const { value } = event.target;\n\n setValue(\n 'slippage',\n formatSlippage(value || defaultSlippage, defaultValue.current, true),\n );\n };\n\n const handleInputBlur: FocusEventHandler = (event) => {\n setFocused(undefined);\n\n const { value } = event.target;\n\n setValue(\n 'slippage',\n formatSlippage(value || defaultSlippage, defaultValue.current),\n );\n };\n\n const customInputValue =\n !slippage || slippage === defaultSlippage ? '' : slippage;\n\n const badgeColor = isSlippageOutsideRecommendedLimits\n ? 'warning'\n : isSlippageChanged\n ? 'info'\n : undefined;\n\n return (\n {`${slippage}%`}\n }\n icon={}\n title={t(`settings.slippage`)}\n >\n \n \n {\n setFocused('button');\n }}\n onBlur={() => {\n setFocused(undefined);\n }}\n onClick={handleDefaultClick}\n disableRipple\n >\n {defaultSlippage}\n \n {\n setFocused('input');\n }}\n onBlur={handleInputBlur}\n value={customInputValue}\n autoComplete=\"off\"\n />\n \n {isSlippageOutsideRecommendedLimits && (\n \n \n \n {t('warning.message.slippageOutsideRecommendedLimits')}\n \n \n )}\n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5M2 13h2c.55 0 1-.45 1-1s-.45-1-1-1H2c-.55 0-1 .45-1 1s.45 1 1 1m18 0h2c.55 0 1-.45 1-1s-.45-1-1-1h-2c-.55 0-1 .45-1 1s.45 1 1 1M11 2v2c0 .55.45 1 1 1s1-.45 1-1V2c0-.55-.45-1-1-1s-1 .45-1 1m0 18v2c0 .55.45 1 1 1s1-.45 1-1v-2c0-.55-.45-1-1-1s-1 .45-1 1M5.99 4.58c-.39-.39-1.03-.39-1.41 0-.39.39-.39 1.03 0 1.41l1.06 1.06c.39.39 1.03.39 1.41 0s.39-1.03 0-1.41zm12.37 12.37c-.39-.39-1.03-.39-1.41 0-.39.39-.39 1.03 0 1.41l1.06 1.06c.39.39 1.03.39 1.41 0 .39-.39.39-1.03 0-1.41zm1.06-10.96c.39-.39.39-1.03 0-1.41-.39-.39-1.03-.39-1.41 0l-1.06 1.06c-.39.39-.39 1.03 0 1.41s1.03.39 1.41 0zM7.05 18.36c.39-.39.39-1.03 0-1.41-.39-.39-1.03-.39-1.41 0l-1.06 1.06c-.39.39-.39 1.03 0 1.41s1.03.39 1.41 0z\"\n}), 'LightMode');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M14 2c1.82 0 3.53.5 5 1.35-2.99 1.73-5 4.95-5 8.65s2.01 6.92 5 8.65c-1.47.85-3.18 1.35-5 1.35-5.52 0-10-4.48-10-10S8.48 2 14 2\"\n}), 'Nightlight');","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M10.85 12.65h2.3L12 9zM20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12zM14.3 16l-.7-2h-3.2l-.7 2H7.8L11 7h2l3.2 9z\"\n}), 'BrightnessAuto');","import { shallow } from 'zustand/shallow';\nimport type { Appearance } from '../../types/widget.js';\nimport { useSettingsStore } from './useSettingsStore.js';\n\nexport const useAppearance = (): [\n Appearance,\n (appearance: Appearance) => void,\n] => {\n const [appearance, setValue] = useSettingsStore(\n (state) => [state.appearance, state.setValue],\n shallow,\n );\n const setAppearance = (appearance: Appearance) => {\n setValue('appearance', appearance);\n };\n return [appearance, setAppearance];\n};\n","import { BrightnessAuto, LightMode, Nightlight } from '@mui/icons-material';\nimport { Tooltip } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { CardValue } from '../../components/Card/CardButton.style.js';\nimport { CardTabs, Tab } from '../../components/Tabs/Tabs.style.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useAppearance } from '../../stores/settings/useAppearance.js';\nimport type { Appearance } from '../../types/widget.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport { SettingCardExpandable } from './SettingsCard/SettingCardExpandable.js';\n\nconst themeIcons = {\n light: LightMode,\n dark: Nightlight,\n auto: BrightnessAuto,\n};\n\ninterface ThemeTabProps {\n title: string;\n value: Appearance;\n Icon: React.ReactElement;\n}\n\n// If the Tab is not the direct child of the Tabs component you can loose the switching\n// The component passes the props to the Tab component so switching isn't lost\nconst ThemeTab: React.FC = ({\n title,\n value,\n Icon,\n ...props\n}) => (\n \n \n \n);\n\nexport const ThemeSettings: React.FC = () => {\n const { t } = useTranslation();\n const [appearance, setAppearance] = useAppearance();\n const { hiddenUI } = useWidgetConfig();\n\n if (hiddenUI?.includes(HiddenUI.Appearance)) {\n return null;\n }\n\n const ThemeIcon = themeIcons[appearance];\n\n const handleThemeChange = (\n _: React.SyntheticEvent,\n appearance: Appearance,\n ) => {\n setAppearance(appearance);\n };\n\n return (\n {t(`button.${appearance}`)} }\n icon={}\n title={t('settings.theme')}\n >\n \n {Object.entries(themeIcons).map(([theme, Icon]) => {\n const supportedThemeOption = theme as Appearance;\n\n return (\n }\n />\n );\n })}\n \n \n );\n};\n","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"absolute\", \"children\", \"className\", \"component\", \"flexItem\", \"light\", \"orientation\", \"role\", \"textAlign\", \"variant\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport { getDividerUtilityClass } from './dividerClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n absolute,\n children,\n classes,\n flexItem,\n light,\n orientation,\n textAlign,\n variant\n } = ownerState;\n const slots = {\n root: ['root', absolute && 'absolute', variant, light && 'light', orientation === 'vertical' && 'vertical', flexItem && 'flexItem', children && 'withChildren', children && orientation === 'vertical' && 'withChildrenVertical', textAlign === 'right' && orientation !== 'vertical' && 'textAlignRight', textAlign === 'left' && orientation !== 'vertical' && 'textAlignLeft'],\n wrapper: ['wrapper', orientation === 'vertical' && 'wrapperVertical']\n };\n return composeClasses(slots, getDividerUtilityClass, classes);\n};\nconst DividerRoot = styled('div', {\n name: 'MuiDivider',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.absolute && styles.absolute, styles[ownerState.variant], ownerState.light && styles.light, ownerState.orientation === 'vertical' && styles.vertical, ownerState.flexItem && styles.flexItem, ownerState.children && styles.withChildren, ownerState.children && ownerState.orientation === 'vertical' && styles.withChildrenVertical, ownerState.textAlign === 'right' && ownerState.orientation !== 'vertical' && styles.textAlignRight, ownerState.textAlign === 'left' && ownerState.orientation !== 'vertical' && styles.textAlignLeft];\n }\n})(({\n theme,\n ownerState\n}) => _extends({\n margin: 0,\n // Reset browser default style.\n flexShrink: 0,\n borderWidth: 0,\n borderStyle: 'solid',\n borderColor: (theme.vars || theme).palette.divider,\n borderBottomWidth: 'thin'\n}, ownerState.absolute && {\n position: 'absolute',\n bottom: 0,\n left: 0,\n width: '100%'\n}, ownerState.light && {\n borderColor: theme.vars ? `rgba(${theme.vars.palette.dividerChannel} / 0.08)` : alpha(theme.palette.divider, 0.08)\n}, ownerState.variant === 'inset' && {\n marginLeft: 72\n}, ownerState.variant === 'middle' && ownerState.orientation === 'horizontal' && {\n marginLeft: theme.spacing(2),\n marginRight: theme.spacing(2)\n}, ownerState.variant === 'middle' && ownerState.orientation === 'vertical' && {\n marginTop: theme.spacing(1),\n marginBottom: theme.spacing(1)\n}, ownerState.orientation === 'vertical' && {\n height: '100%',\n borderBottomWidth: 0,\n borderRightWidth: 'thin'\n}, ownerState.flexItem && {\n alignSelf: 'stretch',\n height: 'auto'\n}), ({\n ownerState\n}) => _extends({}, ownerState.children && {\n display: 'flex',\n whiteSpace: 'nowrap',\n textAlign: 'center',\n border: 0,\n borderTopStyle: 'solid',\n borderLeftStyle: 'solid',\n '&::before, &::after': {\n content: '\"\"',\n alignSelf: 'center'\n }\n}), ({\n theme,\n ownerState\n}) => _extends({}, ownerState.children && ownerState.orientation !== 'vertical' && {\n '&::before, &::after': {\n width: '100%',\n borderTop: `thin solid ${(theme.vars || theme).palette.divider}`,\n borderTopStyle: 'inherit'\n }\n}), ({\n theme,\n ownerState\n}) => _extends({}, ownerState.children && ownerState.orientation === 'vertical' && {\n flexDirection: 'column',\n '&::before, &::after': {\n height: '100%',\n borderLeft: `thin solid ${(theme.vars || theme).palette.divider}`,\n borderLeftStyle: 'inherit'\n }\n}), ({\n ownerState\n}) => _extends({}, ownerState.textAlign === 'right' && ownerState.orientation !== 'vertical' && {\n '&::before': {\n width: '90%'\n },\n '&::after': {\n width: '10%'\n }\n}, ownerState.textAlign === 'left' && ownerState.orientation !== 'vertical' && {\n '&::before': {\n width: '10%'\n },\n '&::after': {\n width: '90%'\n }\n}));\nconst DividerWrapper = styled('span', {\n name: 'MuiDivider',\n slot: 'Wrapper',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.wrapper, ownerState.orientation === 'vertical' && styles.wrapperVertical];\n }\n})(({\n theme,\n ownerState\n}) => _extends({\n display: 'inline-block',\n paddingLeft: `calc(${theme.spacing(1)} * 1.2)`,\n paddingRight: `calc(${theme.spacing(1)} * 1.2)`\n}, ownerState.orientation === 'vertical' && {\n paddingTop: `calc(${theme.spacing(1)} * 1.2)`,\n paddingBottom: `calc(${theme.spacing(1)} * 1.2)`\n}));\nconst Divider = /*#__PURE__*/React.forwardRef(function Divider(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiDivider'\n });\n const {\n absolute = false,\n children,\n className,\n component = children ? 'div' : 'hr',\n flexItem = false,\n light = false,\n orientation = 'horizontal',\n role = component !== 'hr' ? 'separator' : undefined,\n textAlign = 'center',\n variant = 'fullWidth'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n absolute,\n component,\n flexItem,\n light,\n orientation,\n role,\n textAlign,\n variant\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(DividerRoot, _extends({\n as: component,\n className: clsx(classes.root, className),\n role: role,\n ref: ref,\n ownerState: ownerState\n }, other, {\n children: children ? /*#__PURE__*/_jsx(DividerWrapper, {\n className: classes.wrapper,\n ownerState: ownerState,\n children: children\n }) : null\n }));\n});\n\n/**\n * The following flag is used to ensure that this component isn't tabbable i.e.\n * does not get highlight/focus inside of MUI List.\n */\nDivider.muiSkipListHighlight = true;\nprocess.env.NODE_ENV !== \"production\" ? Divider.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Absolutely position the element.\n * @default false\n */\n absolute: PropTypes.bool,\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, a vertical divider will have the correct height when used in flex container.\n * (By default, a vertical divider will have a calculated height of `0px` if it is the child of a flex container.)\n * @default false\n */\n flexItem: PropTypes.bool,\n /**\n * If `true`, the divider will have a lighter color.\n * @default false\n * @deprecated Use (or any opacity or color) instead. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/)\n */\n light: PropTypes.bool,\n /**\n * The component orientation.\n * @default 'horizontal'\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']),\n /**\n * @ignore\n */\n role: PropTypes /* @typescript-to-proptypes-ignore */.string,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The text alignment.\n * @default 'center'\n */\n textAlign: PropTypes.oneOf(['center', 'left', 'right']),\n /**\n * The variant to use.\n * @default 'fullWidth'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['fullWidth', 'inset', 'middle']), PropTypes.string])\n} : void 0;\nexport default Divider;","import { Container as MuiContainer, styled } from '@mui/material';\n\nexport const Container = styled(MuiContainer)(({ theme }) => ({\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: theme.spacing(2),\n}));\n","import { Divider } from '@mui/material';\nimport { Container } from './StepDivider.style.js';\n\nexport const StepDivider: React.FC = () => {\n return (\n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M17 7h-3c-.55 0-1 .45-1 1s.45 1 1 1h3c1.65 0 3 1.35 3 3s-1.35 3-3 3h-3c-.55 0-1 .45-1 1s.45 1 1 1h3c2.76 0 5-2.24 5-5s-2.24-5-5-5m-9 5c0 .55.45 1 1 1h6c.55 0 1-.45 1-1s-.45-1-1-1H9c-.55 0-1 .45-1 1m2 3H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h3c.55 0 1-.45 1-1s-.45-1-1-1H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h3c.55 0 1-.45 1-1s-.45-1-1-1\"\n}), 'LinkRounded');","import type { ProcessStatus, Substatus } from '@lifi/sdk';\nimport type { Theme } from '@mui/material';\nimport {\n Box,\n CircularProgress as MuiCircularProgress,\n alpha,\n circularProgressClasses,\n keyframes,\n styled,\n} from '@mui/material';\n\nconst getStatusColor = (\n theme: Theme,\n status?: ProcessStatus,\n substatus?: Substatus,\n) => {\n switch (status) {\n case 'ACTION_REQUIRED':\n return alpha(theme.palette.info.main, 0.12);\n case 'DONE':\n if (substatus === 'PARTIAL' || substatus === 'REFUNDED') {\n return alpha(theme.palette.warning.main, 0.48);\n }\n return alpha(theme.palette.success.main, 0.12);\n case 'FAILED':\n return alpha(theme.palette.error.main, 0.12);\n default:\n return theme.palette.grey[theme.palette.mode === 'light' ? 300 : 800];\n }\n};\n\nexport const CircularIcon = styled(Box, {\n shouldForwardProp: (prop: string) => !['status', 'substatus'].includes(prop),\n})<{ status?: ProcessStatus; substatus?: Substatus }>(\n ({ theme, status, substatus }) => ({\n backgroundColor: ['ACTION_REQUIRED', 'DONE', 'FAILED'].includes(status!)\n ? getStatusColor(theme, status, substatus)\n : theme.palette.background.paper,\n borderStyle: 'solid',\n borderColor: getStatusColor(theme, status, substatus),\n borderWidth: !['ACTION_REQUIRED', 'DONE', 'FAILED'].includes(status!)\n ? 3\n : 0,\n display: 'grid',\n position: 'relative',\n placeItems: 'center',\n width: 40,\n height: 40,\n borderRadius: '50%',\n }),\n);\n\nconst circleAnimation = keyframes`\n 0% {\n stroke-dashoffset: 129;\n transform: rotate(0);\n }\n 50% {\n stroke-dashoffset: 56;\n transform: rotate(45deg);\n };\n 100% {\n stroke-dashoffset: 129;\n transform: rotate(360deg);\n }\n`;\n\n// This `styled()` function invokes keyframes. `styled-components` only supports keyframes\n// in string templates. Do not convert these styles in JS object as it will break.\nexport const CircularProgressPending = styled(MuiCircularProgress)`\n color: ${({ theme }) =>\n theme.palette.mode === 'light'\n ? theme.palette.primary.main\n : theme.palette.primary.light};\n animation-duration: 3s;\n position: absolute;\n .${circularProgressClasses.circle} {\n animation-duration: 2s;\n animation-timing-function: linear;\n animation-name: ${circleAnimation};\n stroke-dasharray: 129;\n stroke-dashoffset: 129;\n stroke-linecap: round;\n transform-origin: 100% 100%;\n }\n`;\n","import type { LiFiStepExtended } from '@lifi/sdk';\nimport { LinkRounded, Wallet } from '@mui/icons-material';\nimport { Box, Link, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { CardIconButton } from '../Card/CardIconButton.js';\nimport { CircularIcon } from './CircularProgress.style.js';\n\nexport const DestinationWalletAddress: React.FC<{\n step: LiFiStepExtended;\n toAddress: string;\n toAddressLink: string;\n}> = ({ step, toAddress, toAddressLink }) => {\n const { t } = useTranslation();\n const isDone = step.execution?.status === 'DONE';\n return (\n \n \n \n \n \n \n {isDone\n ? t('main.sentToAddress', {\n address: toAddress,\n })\n : t('main.sendToAddress', {\n address: toAddress,\n })}\n \n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M9 16.2 4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z\"\n}), 'Done');","import type { Process } from '@lifi/sdk';\nimport {\n Done,\n ErrorRounded,\n InfoRounded,\n WarningRounded,\n} from '@mui/icons-material';\nimport { darken } from '@mui/material';\nimport {\n CircularIcon,\n CircularProgressPending,\n} from './CircularProgress.style.js';\n\nexport function CircularProgress({ process }: { process: Process }) {\n return (\n \n {process.status === 'STARTED' || process.status === 'PENDING' ? (\n \n ) : null}\n {process.status === 'ACTION_REQUIRED' ? (\n \n ) : null}\n {process.status === 'DONE' &&\n (process.substatus === 'PARTIAL' || process.substatus === 'REFUNDED') ? (\n ({\n position: 'absolute',\n fontSize: '1.5rem',\n color: darken(theme.palette.warning.main, 0.32),\n })}\n />\n ) : process.status === 'DONE' ? (\n \n ) : null}\n {process.status === 'FAILED' ? (\n \n ) : null}\n \n );\n}\n","import type { LiFiStep, Process } from '@lifi/sdk';\nimport { OpenInNewRounded } from '@mui/icons-material';\nimport { Box, Link, Typography } from '@mui/material';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { useProcessMessage } from '../../hooks/useProcessMessage.js';\nimport { CardIconButton } from '../Card/CardIconButton.js';\nimport { CircularProgress } from './CircularProgress.js';\n\nexport const StepProcess: React.FC<{\n step: LiFiStep;\n process: Process;\n}> = ({ step, process }) => {\n const { title, message } = useProcessMessage(step, process);\n const { getTransactionLink } = useExplorer();\n\n return (\n \n \n \n \n {title}\n \n {process.txHash || process.txLink ? (\n \n \n \n ) : null}\n \n {message ? (\n \n {message}\n \n ) : null}\n \n );\n};\n","/* eslint-disable react/no-array-index-key */\nimport type { LiFiStepExtended, TokenAmount } from '@lifi/sdk';\nimport { Box } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { Card } from '../../components/Card/Card.js';\nimport { CardTitle } from '../../components/Card/CardTitle.js';\nimport { StepActions } from '../../components/StepActions/StepActions.js';\nimport { Token } from '../../components/Token/Token.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { DestinationWalletAddress } from './DestinationWalletAddress.js';\nimport { StepProcess } from './StepProcess.js';\nimport { StepTimer } from './StepTimer.js';\n\nexport const Step: React.FC<{\n step: LiFiStepExtended;\n fromToken?: TokenAmount;\n toToken?: TokenAmount;\n impactToken?: TokenAmount;\n toAddress?: string;\n}> = ({ step, fromToken, toToken, impactToken, toAddress }) => {\n const { t } = useTranslation();\n const { subvariant, subvariantOptions } = useWidgetConfig();\n const { getAddressLink } = useExplorer();\n const stepHasError = step.execution?.process.some(\n (process) => process.status === 'FAILED',\n );\n\n const getCardTitle = () => {\n switch (step.type) {\n case 'lifi':\n const hasBridgeStep = step.includedSteps.some(\n (step) => step.type === 'cross',\n );\n const hasSwapStep = step.includedSteps.some(\n (step) => step.type === 'swap',\n );\n if (hasBridgeStep && hasSwapStep) {\n return subvariant === 'custom'\n ? subvariantOptions?.custom === 'deposit'\n ? t('main.stepBridgeAndDeposit')\n : t('main.stepBridgeAndBuy')\n : t('main.stepSwapAndBridge');\n }\n if (hasBridgeStep) {\n return subvariant === 'custom'\n ? subvariantOptions?.custom === 'deposit'\n ? t('main.stepBridgeAndDeposit')\n : t('main.stepBridgeAndBuy')\n : t('main.stepBridge');\n }\n return subvariant === 'custom'\n ? subvariantOptions?.custom === 'deposit'\n ? t('main.stepSwapAndDeposit')\n : t('main.stepSwapAndBuy')\n : t('main.stepSwap');\n default:\n return subvariant === 'custom'\n ? subvariantOptions?.custom === 'deposit'\n ? t('main.stepSwapAndDeposit')\n : t('main.stepSwapAndBuy')\n : t('main.stepSwap');\n }\n };\n\n const formattedToAddress = shortenAddress(toAddress);\n const toAddressLink = toAddress\n ? getAddressLink(toAddress, step.action.toChainId)\n : undefined;\n\n return (\n \n \n {getCardTitle()}\n \n \n \n \n \n {fromToken ? : null}\n \n {step.execution?.process.map((process, index) => (\n \n ))}\n {formattedToAddress && toAddressLink ? (\n \n ) : null}\n {toToken ? (\n \n ) : null}\n \n \n );\n};\n","import type { RouteExtended, TokenAmount } from '@lifi/sdk';\nimport { Fragment } from 'react';\nimport { StepDivider } from '../../components/StepDivider/StepDivider.js';\nimport type { WidgetSubvariant } from '../../types/widget.js';\nimport { Step } from './Step.js';\n\nexport const getStepList = (\n route?: RouteExtended,\n subvariant?: WidgetSubvariant,\n) =>\n route?.steps.map((step, index, steps) => {\n const lastIndex = steps.length - 1;\n const fromToken: TokenAmount | undefined =\n index === 0\n ? {\n ...step.action.fromToken,\n amount: BigInt(step.action.fromAmount),\n }\n : undefined;\n let toToken: TokenAmount | undefined;\n let impactToken: TokenAmount | undefined;\n if (index === lastIndex) {\n toToken = {\n ...(step.execution?.toToken ?? step.action.toToken),\n amount: step.execution?.toAmount\n ? BigInt(step.execution.toAmount)\n : subvariant === 'custom'\n ? BigInt(route.toAmount)\n : BigInt(step.estimate.toAmount),\n };\n impactToken = {\n ...steps[0].action.fromToken,\n amount: BigInt(steps[0].action.fromAmount),\n };\n }\n const toAddress =\n index === lastIndex && route.fromAddress !== route.toAddress\n ? route.toAddress\n : undefined;\n return (\n \n \n {steps.length > 1 && index !== steps.length - 1 ? (\n \n ) : null}\n \n );\n });\n","import type { RouteExtended } from '@lifi/sdk';\nimport {\n ExpandLess,\n ExpandMore,\n LocalGasStationRounded,\n} from '@mui/icons-material';\nimport type { CardProps } from '@mui/material';\nimport { Box, Collapse, Tooltip, Typography } from '@mui/material';\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { formatUnits } from 'viem';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { isRouteDone } from '../stores/routes/utils.js';\nimport { getAccumulatedFeeCostsBreakdown } from '../utils/fees.js';\nimport { formatTokenAmount, formatTokenPrice } from '../utils/format.js';\nimport { Card } from './Card/Card.js';\nimport { CardIconButton } from './Card/CardIconButton.js';\nimport { FeeBreakdownTooltip } from './FeeBreakdownTooltip.js';\nimport { IconTypography } from './IconTypography.js';\nimport { TokenRate } from './TokenRate/TokenRate.js';\n\ninterface TransactionDetailsProps extends CardProps {\n route: RouteExtended;\n}\n\nexport const TransactionDetails: React.FC = ({\n route,\n ...props\n}) => {\n const { t } = useTranslation();\n const { feeConfig } = useWidgetConfig();\n const [cardExpanded, setCardExpanded] = useState(false);\n\n const toggleCard = () => {\n setCardExpanded((cardExpanded) => !cardExpanded);\n };\n const { gasCosts, feeCosts, gasCostUSD, feeCostUSD, combinedFeesUSD } =\n getAccumulatedFeeCostsBreakdown(route);\n\n const fromTokenAmount = formatTokenAmount(\n BigInt(route.fromAmount),\n route.fromToken.decimals,\n );\n const fromTokenPrice = formatTokenPrice(\n fromTokenAmount,\n route.fromToken.priceUSD,\n );\n const toTokenAmount = formatTokenAmount(\n BigInt(route.toAmount),\n route.toToken.decimals,\n );\n const toTokenPrice =\n formatTokenPrice(toTokenAmount, route.toToken.priceUSD) || 0.01;\n\n const priceImpact = toTokenPrice / fromTokenPrice - 1;\n\n const feeCollectionStep = route.steps[0].includedSteps.find(\n (includedStep) => includedStep.tool === 'feeCollection',\n );\n\n let feeAmountUSD: number = 0;\n\n if (feeCollectionStep) {\n const estimatedFromAmount =\n BigInt(feeCollectionStep.estimate.fromAmount) -\n BigInt(feeCollectionStep.estimate.toAmount);\n\n const feeAmount = formatUnits(\n estimatedFromAmount,\n feeCollectionStep.action.fromToken.decimals,\n );\n\n feeAmountUSD =\n parseFloat(feeAmount) *\n parseFloat(feeCollectionStep.action.fromToken.priceUSD);\n }\n\n const showIntegratorFeeCollectionDetails =\n feeAmountUSD || Number.isFinite(feeConfig?.fee);\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n {t(`format.currency`, { value: combinedFeesUSD })}\n \n \n \n \n \n {cardExpanded ? (\n \n ) : (\n \n )}\n \n \n \n \n \n {t('main.fees.network')}\n \n \n {t(`format.currency`, {\n value: gasCostUSD,\n })}\n \n \n \n {feeCosts.length ? (\n \n {t('main.fees.provider')}\n \n \n {t(`format.currency`, {\n value: feeCostUSD,\n })}\n \n \n \n ) : null}\n {showIntegratorFeeCollectionDetails ? (\n \n \n {feeConfig?.name\n ? t('main.fees.integrator', { tool: feeConfig.name })\n : t('main.fees.defaultIntegrator')}\n \n {feeConfig?.name ? (\n \n \n {t(`format.currency`, {\n value: feeAmountUSD,\n })}\n \n \n ) : (\n \n {t(`format.currency`, {\n value: feeAmountUSD,\n })}\n \n )}\n \n ) : null}\n \n {t('main.priceImpact')}\n \n \n {t('format.percent', { value: priceImpact })}\n \n \n \n {!isRouteDone(route) ? (\n <>\n \n {t('main.maxSlippage')}\n \n \n {t('format.percent', {\n value: route.steps[0].action.slippage,\n })}\n \n \n \n \n {t('main.minReceived')}\n \n \n {t('format.number', {\n value: formatTokenAmount(\n BigInt(route.toAmountMin),\n route.toToken.decimals,\n ),\n })}{' '}\n {route.toToken.symbol}\n \n \n \n \n ) : null}\n \n \n \n );\n};\n","import type {\n ExtendedTransactionInfo,\n FeeCost,\n FullStatusData,\n Process,\n ProcessStatus,\n Substatus,\n TokenAmount,\n ToolsResponse,\n} from '@lifi/sdk';\nimport { v4 as uuidv4 } from 'uuid';\nimport { formatUnits } from 'viem';\nimport type { RouteExecution } from '../stores/routes/types.js';\n\nconst buildProcessFromTxHistory = (tx: FullStatusData): Process[] => {\n const sending = tx.sending as ExtendedTransactionInfo;\n const receiving = tx.receiving as ExtendedTransactionInfo;\n\n if (!sending.token?.chainId || !receiving.token?.chainId) {\n return [];\n }\n\n const processStatus: ProcessStatus = tx.status === 'DONE' ? 'DONE' : 'FAILED';\n const substatus: Substatus =\n processStatus === 'FAILED' ? 'UNKNOWN_ERROR' : 'COMPLETED';\n\n if (sending.chainId === receiving.chainId) {\n return [\n {\n type: 'SWAP', // operations on same chain will be swaps\n startedAt: sending.timestamp ?? Date.now(),\n message: '',\n status: processStatus,\n txHash: sending.txHash,\n txLink: sending.txLink,\n doneAt: receiving.timestamp ?? Date.now(),\n substatus,\n substatusMessage: '',\n },\n ];\n }\n\n const process: Process[] = [\n {\n type: 'CROSS_CHAIN', // first step of bridging, ignoring the approvals\n startedAt: sending.timestamp ?? Date.now(),\n message: '',\n status: processStatus, // can be FAILED\n txHash: sending.txHash,\n txLink: sending.txLink,\n doneAt: sending.timestamp,\n },\n {\n type: 'RECEIVING_CHAIN', // final step of bridging, post swaps\n startedAt: receiving.timestamp ?? Date.now(),\n message: '',\n status: processStatus,\n substatus,\n substatusMessage: '',\n doneAt: receiving.timestamp ?? Date.now(),\n txHash: receiving.txHash,\n txLink: receiving.txLink,\n },\n ];\n\n return process;\n};\n\nexport const buildRouteFromTxHistory = (\n tx: FullStatusData,\n tools?: ToolsResponse,\n) => {\n const sending = tx.sending as ExtendedTransactionInfo;\n const receiving = tx.receiving as ExtendedTransactionInfo;\n\n if (!sending.token?.chainId || !receiving.token?.chainId) {\n return;\n }\n\n const selectedBridge = tools?.bridges.find(\n (bridge) => bridge.key === tx.tool,\n );\n\n const selectedExchange = tools?.exchanges.find(\n (exchange) => exchange.key === tx.tool,\n );\n\n const usedTool = {\n key: tx.tool,\n name: selectedBridge?.name ?? selectedExchange?.name ?? tx.tool,\n logoURI: selectedBridge?.logoURI ?? selectedExchange?.logoURI ?? '',\n };\n\n const fromToken: TokenAmount = {\n ...sending.token,\n amount: BigInt(sending.amount ?? 0),\n };\n\n const toToken: TokenAmount = {\n ...receiving.token,\n amount: BigInt(receiving.amount ?? 0),\n };\n\n const sendingValue = sending.value ? BigInt(sending.value) : 0n;\n const sendingFeeAmount =\n sending.gasToken.address === sending.token.address && sending.amount\n ? sendingValue - BigInt(sending.amount)\n : sendingValue;\n const sendingFeeAmountUsd =\n sending.gasToken.priceUSD && sendingFeeAmount\n ? parseFloat(formatUnits(sendingFeeAmount, sending.gasToken.decimals)) *\n parseFloat(sending.gasToken.priceUSD)\n : 0;\n\n const feeCosts: FeeCost[] | undefined = sendingFeeAmount\n ? [\n {\n amount: sendingFeeAmount.toString(),\n amountUSD: sendingFeeAmountUsd.toFixed(2),\n token: sending.gasToken,\n included: false,\n // Not used\n description: '',\n name: '',\n percentage: '',\n },\n ]\n : undefined;\n\n const routeExecution: RouteExecution = {\n status: 1,\n route: {\n id: (tx as FullStatusData).transactionId,\n fromAddress: (tx as FullStatusData).fromAddress,\n toAddress: (tx as FullStatusData).toAddress,\n fromChainId: sending.chainId,\n fromAmount: sending.amount ?? '',\n fromAmountUSD: sending.amountUSD ?? '',\n toAmount: receiving.amount ?? '',\n toAmountMin: receiving.amount ?? '',\n toAmountUSD: receiving.amountUSD ?? '',\n toChainId: receiving.chainId,\n fromToken,\n toToken,\n gasCostUSD: sending.gasAmountUSD,\n steps: [\n {\n id: uuidv4(),\n type: 'lifi',\n tool: tx.tool,\n toolDetails: usedTool,\n action: {\n fromToken: sending.token,\n fromAmount: sending.amount ?? '',\n fromChainId: sending.chainId,\n fromAddress: (tx as FullStatusData).fromAddress,\n toToken: receiving.token,\n toChainId: receiving.chainId,\n toAddress: (tx as FullStatusData).toAddress,\n slippage: 0,\n },\n estimate: {\n tool: tx.tool,\n approvalAddress: '',\n fromAmount: sending.amount ?? '',\n fromAmountUSD: sending.amountUSD ?? '',\n toAmountMin: receiving.amount ?? '',\n toAmount: receiving.amount ?? '',\n toAmountUSD: receiving.amountUSD ?? '',\n executionDuration: 0,\n },\n includedSteps: [\n {\n id: '',\n type: sending.chainId === receiving.chainId ? 'swap' : 'cross',\n action: {\n fromChainId: sending.chainId,\n fromAmount: sending.amount ?? '',\n fromToken: sending.token,\n toChainId: receiving.chainId,\n toToken: receiving.token,\n slippage: 0,\n fromAddress: (tx as FullStatusData).fromAddress,\n toAddress: (tx as FullStatusData).toAddress,\n },\n estimate: {\n tool: tx.tool,\n fromAmount: sending.amount ?? '',\n toAmount: receiving.amount ?? '',\n toAmountMin: receiving.amount ?? '',\n approvalAddress: '',\n executionDuration: 0,\n },\n tool: tx.tool,\n toolDetails: usedTool,\n },\n ],\n integrator: tx.metadata?.integrator ?? '',\n execution: {\n status: 'DONE', // can be FAILED\n process: buildProcessFromTxHistory(tx),\n fromAmount: sending.amount,\n toAmount: receiving.amount,\n toToken: receiving.token,\n gasCosts: [\n {\n amount: sending.gasAmount,\n amountUSD: sending.gasAmountUSD,\n token: sending.gasToken,\n estimate: '0',\n limit: '0',\n price: '0',\n type: 'SEND',\n },\n ],\n feeCosts,\n },\n },\n ],\n insurance: {\n state: 'NOT_INSURABLE',\n feeAmountUsd: '0',\n },\n },\n };\n\n return routeExecution;\n};\n","import { Button } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { WidgetEvent } from '../../types/events.js';\n\ninterface ContactSupportButtonProps {\n supportId?: string;\n}\n\nexport const ContactSupportButton = ({\n supportId,\n}: ContactSupportButtonProps) => {\n const { t } = useTranslation();\n const widgetEvents = useWidgetEvents();\n\n const handleClick = () => {\n if (!widgetEvents.all.has(WidgetEvent.ContactSupport)) {\n const url = 'https://discord.gg/lifi';\n const target = '_blank';\n const rel = 'nofollow noreferrer';\n window.open(url, target, rel);\n } else {\n widgetEvents.emit(WidgetEvent.ContactSupport, { supportId });\n }\n };\n\n return (\n \n );\n};\n","import { Box, Skeleton } from '@mui/material';\nimport { Card } from '../../components/Card/Card.js';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { TokenSkeleton } from '../../components/Token/Token.js';\n\nexport const TransactionDetailsSkeleton = () => {\n return (\n \n \n \n \n \n \n \n \n \n \n {/* Token skeleton */}\n \n \n \n {/* Bridge skeleton */}\n \n \n \n {/* Steps skeleton */}\n {Array.from({ length: 3 }).map((_, key) => (\n \n \n \n \n ))}\n {/* Receiving Token skeleton */}\n \n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z\"\n}), 'OpenInNew');","import { ContentCopyRounded, OpenInNew } from '@mui/icons-material';\nimport { Box, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { Card } from '../../components/Card/Card.js';\nimport { CardIconButton } from '../../components/Card/CardIconButton.js';\nimport { CardTitle } from '../../components/Card/CardTitle.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\n\ninterface TransferIdCardProps {\n transferId: string;\n}\n\nconst getTxHash = (transferId: string) =>\n transferId.indexOf('_') !== -1\n ? transferId.substring(0, transferId.indexOf('_'))\n : transferId;\n\nexport const TransferIdCard = ({ transferId }: TransferIdCardProps) => {\n const { t } = useTranslation();\n const { getTransactionLink } = useExplorer();\n\n const copyTransferId = async () => {\n await navigator.clipboard.writeText(transferId);\n };\n\n const openTransferIdInExplorer = () => {\n const txHash = getTxHash(transferId);\n window.open(getTransactionLink({ txHash }), '_blank');\n };\n\n return (\n \n \n {t('main.transferId')}\n \n \n \n \n \n \n \n \n \n \n {transferId}\n \n \n );\n};\n","import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep } from './utils'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { NotifyOptions } from './queryObserver'\n\nfunction difference(array1: Array, array2: Array): Array {\n return array1.filter((x) => !array2.includes(x))\n}\n\nfunction replaceAt(array: Array, index: number, value: T): Array {\n const copy = array.slice(0)\n copy[index] = value\n return copy\n}\n\ntype QueriesObserverListener = (result: Array) => void\n\ntype CombineFn = (\n result: Array,\n) => TCombinedResult\n\nexport interface QueriesObserverOptions<\n TCombinedResult = Array,\n> {\n combine?: CombineFn\n}\n\nexport class QueriesObserver<\n TCombinedResult = Array,\n> extends Subscribable {\n #client: QueryClient\n #result!: Array\n #queries: Array\n #observers: Array\n #combinedResult?: TCombinedResult\n #lastCombine?: CombineFn\n #lastResult?: Array\n\n constructor(\n client: QueryClient,\n queries: Array>,\n _options?: QueriesObserverOptions,\n ) {\n super()\n\n this.#client = client\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n setQueries(\n queries: Array,\n _options?: QueriesObserverOptions,\n notifyOptions?: NotifyOptions,\n ): void {\n this.#queries = queries\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),\n )\n\n const newObservers = newObserverMatches.map((match) => match.observer)\n const newResult = newObservers.map((observer) =>\n observer.getCurrentResult(),\n )\n\n const hasIndexChange = newObservers.some(\n (observer, index) => observer !== prevObservers[index],\n )\n\n if (prevObservers.length === newObservers.length && !hasIndexChange) {\n return\n }\n\n this.#observers = newObservers\n this.#result = newResult\n\n if (!this.hasListeners()) {\n return\n }\n\n difference(prevObservers, newObservers).forEach((observer) => {\n observer.destroy()\n })\n\n difference(newObservers, prevObservers).forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n\n this.#notify()\n })\n }\n\n getCurrentResult(): Array {\n return this.#result\n }\n\n getQueries() {\n return this.#observers.map((observer) => observer.getCurrentQuery())\n }\n\n getObservers() {\n return this.#observers\n }\n\n getOptimisticResult(\n queries: Array,\n combine: CombineFn | undefined,\n ): [\n rawResult: Array,\n combineResult: (r?: Array) => TCombinedResult,\n trackResult: () => Array,\n ] {\n const matches = this.#findMatchingObservers(queries)\n const result = matches.map((match) =>\n match.observer.getOptimisticResult(match.defaultedQueryOptions),\n )\n\n return [\n result,\n (r?: Array) => {\n return this.#combineResult(r ?? result, combine)\n },\n () => {\n return matches.map((match, index) => {\n const observerResult = result[index]!\n return !match.defaultedQueryOptions.notifyOnChangeProps\n ? match.observer.trackResult(observerResult, (accessedProp) => {\n // track property on all observers to ensure proper (synchronized) tracking (#7000)\n matches.forEach((m) => {\n m.observer.trackProp(accessedProp)\n })\n })\n : observerResult\n })\n },\n ]\n }\n\n #combineResult(\n input: Array,\n combine: CombineFn | undefined,\n ): TCombinedResult {\n if (combine) {\n if (\n !this.#combinedResult ||\n this.#result !== this.#lastResult ||\n combine !== this.#lastCombine\n ) {\n this.#lastCombine = combine\n this.#lastResult = this.#result\n this.#combinedResult = replaceEqualDeep(\n this.#combinedResult,\n combine(input),\n )\n }\n\n return this.#combinedResult\n }\n return input as any\n }\n\n #findMatchingObservers(\n queries: Array,\n ): Array {\n const prevObservers = this.#observers\n const prevObserversMap = new Map(\n prevObservers.map((observer) => [observer.options.queryHash, observer]),\n )\n\n const defaultedQueryOptions = queries.map((options) =>\n this.#client.defaultQueryOptions(options),\n )\n\n const matchingObservers: Array =\n defaultedQueryOptions.flatMap((defaultedOptions) => {\n const match = prevObserversMap.get(defaultedOptions.queryHash)\n if (match != null) {\n return [{ defaultedQueryOptions: defaultedOptions, observer: match }]\n }\n return []\n })\n\n const matchedQueryHashes = new Set(\n matchingObservers.map((match) => match.defaultedQueryOptions.queryHash),\n )\n const unmatchedQueries = defaultedQueryOptions.filter(\n (defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash),\n )\n\n const getObserver = (options: QueryObserverOptions): QueryObserver => {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n const currentObserver = this.#observers.find(\n (o) => o.options.queryHash === defaultedOptions.queryHash,\n )\n return (\n currentObserver ?? new QueryObserver(this.#client, defaultedOptions)\n )\n }\n\n const newOrReusedObservers: Array =\n unmatchedQueries.map((options) => {\n return {\n defaultedQueryOptions: options,\n observer: getObserver(options),\n }\n })\n\n const sortMatchesByOrderOfQueries = (\n a: QueryObserverMatch,\n b: QueryObserverMatch,\n ): number =>\n defaultedQueryOptions.indexOf(a.defaultedQueryOptions) -\n defaultedQueryOptions.indexOf(b.defaultedQueryOptions)\n\n return matchingObservers\n .concat(newOrReusedObservers)\n .sort(sortMatchesByOrderOfQueries)\n }\n\n #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {\n const index = this.#observers.indexOf(observer)\n if (index !== -1) {\n this.#result = replaceAt(this.#result, index, result)\n this.#notify()\n }\n }\n\n #notify(): void {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(this.#result)\n })\n })\n }\n}\n\ntype QueryObserverMatch = {\n defaultedQueryOptions: DefaultedQueryObserverOptions\n observer: QueryObserver\n}\n","import type { FullStatusData, StatusResponse } from '@lifi/sdk';\nimport { getTransactionHistory, type ExtendedTransactionInfo } from '@lifi/sdk';\nimport type { QueryFunction } from '@tanstack/react-query';\nimport { useQueries } from '@tanstack/react-query';\nimport { useAccount } from './useAccount.js';\n\nexport const useTransactionHistory = () => {\n const { accounts } = useAccount();\n\n const { data, isLoading } = useQueries({\n queries: accounts.map((account) => ({\n queryKey: ['transaction-history', account.address],\n queryFn: (async ({ queryKey: [, accountAddress], signal }) => {\n if (!accountAddress) {\n return [];\n }\n const date = new Date();\n date.setFullYear(date.getFullYear() - 10);\n\n const response = await getTransactionHistory(\n {\n wallet: accountAddress,\n fromTimestamp: Math.floor(date.getTime() / 1000),\n toTimestamp: Math.floor(Date.now() / 1000),\n },\n { signal },\n );\n\n return response.transfers;\n }) as QueryFunction,\n refetchInterval: 300_000,\n enabled: Boolean(account.address),\n })),\n combine: (results) => {\n const uniqueTransactions = new Map();\n results.forEach((result) => {\n if (result.data) {\n result.data.forEach((transaction) => {\n if (\n (transaction as FullStatusData)?.transactionId &&\n (transaction as FullStatusData)?.receiving?.chainId &&\n transaction?.sending.chainId\n ) {\n uniqueTransactions.set(\n (transaction as FullStatusData).transactionId,\n transaction,\n );\n }\n });\n }\n });\n const data = Array.from(uniqueTransactions.values()).sort((a, b) => {\n return (\n ((b?.sending as ExtendedTransactionInfo)?.timestamp ?? 0) -\n ((a?.sending as ExtendedTransactionInfo)?.timestamp ?? 0)\n );\n }) as StatusResponse[];\n return {\n data: data,\n isLoading: results.some((result) => result.isLoading),\n };\n },\n });\n\n return {\n data,\n isLoading,\n };\n};\n","'use client'\nimport * as React from 'react'\n\nimport {\n QueriesObserver,\n QueryObserver,\n notifyManager,\n} from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useIsRestoring } from './isRestoring'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions,\n 'placeholderData'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult\n : TInitialData extends TData\n ? DefinedUseQueryResult\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult\n : UseQueryResult\n : UseQueryResult\n : UseQueryResult\n\ntype GetUseQueryResult =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * QueriesOptions reducer recursively unwraps function arguments to infer/enforce type param\n */\nexport type QueriesOptions<\n T extends Array,\n TResults extends Array = [],\n TDepth extends ReadonlyArray = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries],\n [...TDepth, 1]\n >\n : ReadonlyArray extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogenous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array\n\n/**\n * QueriesResults reducer recursively maps type param to results\n */\nexport type QueriesResults<\n T extends Array,\n TResults extends Array = [],\n TDepth extends ReadonlyArray = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult],\n [...TDepth, 1]\n >\n : T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n any\n >\n >\n ? // Dynamic-size (homogenous) UseQueryOptions array: map directly to array of results\n Array<\n UseQueryResult<\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n >\n : // Fallback\n Array\n\nexport function useQueries<\n T extends Array,\n TCombinedResult = QueriesResults,\n>(\n {\n queries,\n ...options\n }: {\n queries: readonly [...QueriesOptions]\n combine?: (result: QueriesResults) => TCombinedResult\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n\n const defaultedQueries = React.useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions\n }),\n [queries, client, isRestoring],\n )\n\n defaultedQueries.forEach((query) => {\n ensureSuspenseTimers(query)\n ensurePreventErrorBoundaryRetry(query, errorResetBoundary)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = React.useState(\n () =>\n new QueriesObserver(\n client,\n defaultedQueries,\n options as QueriesObserverOptions,\n ),\n )\n\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions).combine,\n )\n\n React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n isRestoring\n ? () => undefined\n : observer.subscribe(notifyManager.batchCalls(onStoreChange)),\n [observer, isRestoring],\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult(),\n )\n\n React.useEffect(() => {\n // Do not notify on updates because of changes in the options because\n // these changes should already be reflected in the optimistic result.\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions,\n {\n listeners: false,\n },\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts) {\n const queryObserver = new QueryObserver(client, opts)\n if (shouldSuspend(opts, result)) {\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n } else if (willFetch(result, isRestoring)) {\n void fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow?.error) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon([/*#__PURE__*/_jsx(\"path\", {\n d: \"M14 9h-4c-.55 0-1-.45-1-1s.45-1 1-1h4c.55 0 1 .45 1 1s-.45 1-1 1m0 3h-4c-.55 0-1-.45-1-1s.45-1 1-1h4c.55 0 1 .45 1 1s-.45 1-1 1\"\n}, \"0\"), /*#__PURE__*/_jsx(\"path\", {\n d: \"M19.5 3.5 18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2v14H4c-.55 0-1 .45-1 1v2c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V2zM15 20H6c-.55 0-1-.45-1-1v-1h10zm4-1c0 .55-.45 1-1 1s-1-.45-1-1v-2c0-.55-.45-1-1-1H8V5h11z\"\n}, \"1\"), /*#__PURE__*/_jsx(\"circle\", {\n cx: \"17\",\n cy: \"8\",\n r: \"1\"\n}, \"2\"), /*#__PURE__*/_jsx(\"circle\", {\n cx: \"17\",\n cy: \"11\",\n r: \"1\"\n}, \"3\")], 'ReceiptLongRounded');","import { ReceiptLongRounded } from '@mui/icons-material';\nimport { Container, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\n\nexport const TransactionHistoryEmpty: React.FC = () => {\n const { t } = useTranslation();\n return (\n \n \n \n \n \n {t('info.title.emptyTransactionHistory')}\n \n \n {t('info.message.emptyTransactionHistory')}\n \n \n );\n};\n","import type {\n ExtendedTransactionInfo,\n FullStatusData,\n StatusResponse,\n TokenAmount,\n} from '@lifi/sdk';\nimport { Box, Typography } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { Card } from '../../components/Card/Card.js';\nimport { Token } from '../../components/Token/Token.js';\nimport { TokenDivider } from '../../components/Token/Token.style.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\n\nexport const TransactionHistoryItem: React.FC<{\n transaction: StatusResponse;\n size: number;\n start: number;\n}> = ({ transaction, size, start }) => {\n const { i18n } = useTranslation();\n const navigate = useNavigate();\n\n const sending = transaction.sending as ExtendedTransactionInfo;\n const receiving = (transaction as FullStatusData)\n .receiving as ExtendedTransactionInfo;\n\n const handleClick = () => {\n navigate(navigationRoutes.transactionDetails, {\n state: {\n transactionHash: (transaction as FullStatusData).sending.txHash,\n },\n });\n };\n\n const startedAt = new Date((sending.timestamp ?? 0) * 1000);\n\n if (!sending.token?.chainId || !receiving.token?.chainId) {\n return null;\n }\n\n const fromToken: TokenAmount = {\n ...sending.token,\n amount: BigInt(sending.amount ?? '0'),\n priceUSD: sending.token.priceUSD ?? '0',\n symbol: sending.token?.symbol ?? '',\n decimals: sending.token?.decimals ?? 0,\n name: sending.token?.name ?? '',\n chainId: sending.token?.chainId,\n };\n\n const toToken: TokenAmount = {\n ...receiving.token,\n amount: BigInt(receiving.amount ?? '0'),\n priceUSD: receiving.token.priceUSD ?? '0',\n symbol: receiving.token?.symbol ?? '',\n decimals: receiving.token?.decimals ?? 0,\n name: receiving.token?.name ?? '',\n chainId: receiving.token?.chainId,\n };\n\n return (\n \n \n \n {startedAt.toLocaleString(i18n.language, { dateStyle: 'long' })}\n \n \n {startedAt.toLocaleString(i18n.language, {\n timeStyle: 'short',\n })}\n \n \n \n \n \n \n \n \n \n \n );\n};\n","import { Box, Skeleton } from '@mui/material';\nimport { Card } from '../../components/Card/Card.js';\nimport { TokenSkeleton } from '../../components/Token/Token.js';\nimport { TokenDivider } from '../../components/Token/Token.style.js';\n\nexport const TransactionHistoryItemSkeleton = () => {\n return (\n \n \n ({\n borderRadius: `${theme.shape.borderRadius}px`,\n })}\n />\n ({\n borderRadius: `${theme.shape.borderRadius}px`,\n })}\n />\n \n \n \n \n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z\"\n}), 'Delete');","import type { MutableRefObject } from 'react';\nimport { useLayoutEffect } from 'react';\nimport { getRelativeContainer } from '../utils/elements.js';\nimport { useDefaultElementId } from './useDefaultElementId.js';\n\n// NOTE: this hook is implicitly tied to the widget height functionality in the\n// AppExpandedContainer, RelativeContainer and CssBaselineContainer components as defined in AppContainer.ts\n// CSS changes in those components can have implications for the functionality in this hook\n\nexport const useSetContentHeight = (\n ref: MutableRefObject,\n) => {\n const elementId = useDefaultElementId();\n useLayoutEffect(() => {\n const relativeContainer = getRelativeContainer(elementId);\n if (\n !relativeContainer ||\n !ref.current ||\n ref.current?.clientHeight <= relativeContainer?.clientHeight\n ) {\n return;\n }\n relativeContainer.style.minHeight = `${ref.current.clientHeight}px`;\n return () => {\n relativeContainer.style.removeProperty('min-height');\n };\n }, [elementId, ref]);\n};\n","import type { Theme } from '@mui/material';\nimport { Box, alpha, darken, styled } from '@mui/material';\nimport { RouteExecutionStatus } from '../../stores/routes/types.js';\n\ntype StatusColor = RouteExecutionStatus | 'warning';\n\nconst getStatusColor = (status: StatusColor, theme: Theme) => {\n switch (status) {\n case RouteExecutionStatus.Done:\n return { color: theme.palette.success.main, alpha: 0.12, darken: 0 };\n case RouteExecutionStatus.Failed:\n return { color: theme.palette.error.main, alpha: 0.12, darken: 0 };\n case RouteExecutionStatus.Done | RouteExecutionStatus.Partial:\n case RouteExecutionStatus.Done | RouteExecutionStatus.Refunded:\n case 'warning':\n return {\n color: theme.palette.warning.main,\n alpha: 0.48,\n darken: theme.palette.mode === 'light' ? 0.32 : 0,\n };\n default:\n return { color: theme.palette.primary.main, alpha: 0.12, darken: 0 };\n }\n};\n\nexport const CenterContainer = styled(Box)(({ theme }) => ({\n display: 'grid',\n placeItems: 'center',\n position: 'relative',\n}));\n\nexport const IconCircle = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'status',\n})<{ status: StatusColor }>(({ theme, status }) => {\n const {\n color,\n alpha: alphaValue,\n darken: darkenValue,\n } = getStatusColor(status, theme);\n return {\n backgroundColor: alpha(color, alphaValue),\n borderRadius: '50%',\n width: 64,\n height: 64,\n display: 'grid',\n position: 'relative',\n placeItems: 'center',\n '& > svg': {\n color: darken(color, darkenValue),\n width: 32,\n height: 32,\n },\n };\n});\n\nexport const MessageSkeletonContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n height: 64,\n gap: theme.spacing(0.5),\n paddingTop: theme.spacing(1),\n}));\n","import type { ExchangeRateUpdateParams } from '@lifi/sdk';\nimport { WarningRounded } from '@mui/icons-material';\nimport { Box, Button, Typography } from '@mui/material';\nimport type { MutableRefObject } from 'react';\nimport {\n forwardRef,\n useCallback,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { BottomSheet } from '../../components/BottomSheet/BottomSheet.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { useSetContentHeight } from '../../hooks/useSetContentHeight.js';\nimport { formatTokenAmount } from '../../utils/format.js';\nimport { CenterContainer, IconCircle } from './StatusBottomSheet.style.js';\n\nexport interface ExchangeRateBottomSheetBase {\n isOpen(): void;\n open(\n resolver: (value: boolean) => void,\n data: ExchangeRateUpdateParams,\n ): void;\n close(value?: boolean, bottomSheetClose?: boolean): void;\n}\n\ninterface ExchangeRateBottomSheetProps {\n data?: ExchangeRateUpdateParams;\n onContinue?(): void;\n onCancel?(): void;\n}\n\nexport const ExchangeRateBottomSheet = forwardRef<\n ExchangeRateBottomSheetBase,\n ExchangeRateBottomSheetProps\n>(({ onContinue, onCancel }, ref) => {\n const [data, setData] = useState();\n const bottomSheetRef = useRef(null);\n const resolverRef = useRef<(value: boolean) => void>();\n\n const handleContinue = () => {\n (ref as MutableRefObject).current?.close(true);\n onContinue?.();\n };\n\n const handleCancel = useCallback(() => {\n (ref as MutableRefObject).current?.close(\n false,\n );\n onCancel?.();\n }, [onCancel, ref]);\n\n const handleClose = useCallback(() => {\n (ref as MutableRefObject).current?.close(\n false,\n false,\n );\n onCancel?.();\n }, [onCancel, ref]);\n\n useImperativeHandle(\n ref,\n () => ({\n isOpen: () => bottomSheetRef.current?.isOpen(),\n open: (resolver, data) => {\n setData(data);\n resolverRef.current = resolver;\n bottomSheetRef.current?.open();\n },\n close: (value = false, bottomSheetClose = true) => {\n resolverRef.current?.(value);\n if (bottomSheetClose) {\n bottomSheetRef.current?.close();\n }\n },\n }),\n [],\n );\n\n return (\n \n \n \n );\n});\n\nconst ExchangeRateBottomSheetContent: React.FC<\n ExchangeRateBottomSheetProps\n> = ({ data, onCancel, onContinue }) => {\n const { t } = useTranslation();\n const ref = useRef();\n useSetContentHeight(ref);\n\n if (!data) {\n return;\n }\n\n const oldAmount = BigInt(data.oldToAmount || 1);\n const rateChange = (\n (Number((BigInt(data.newToAmount || 0) * 1_000_000n) / oldAmount) /\n 1_000_000) *\n 100 -\n 100\n ).toFixed(2);\n\n return (\n \n \n \n \n \n \n {t('warning.title.rateChanged')}\n \n \n {t('warning.message.rateChanged')}\n \n {t('main.quotedAmount')}\n \n {t('format.number', {\n value: formatTokenAmount(\n BigInt(data.oldToAmount),\n data.toToken.decimals,\n ),\n })}{' '}\n {data?.toToken.symbol}\n \n \n \n {t('main.currentAmount')}\n \n {t('format.number', {\n value: formatTokenAmount(\n BigInt(data?.newToAmount),\n data?.toToken.decimals,\n ),\n })}{' '}\n {data?.toToken.symbol}\n \n \n \n {t('main.rateChange')}\n {rateChange}%\n \n \n \n \n \n \n \n );\n};\n","import type { Dispatch, SetStateAction } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { ProgressToNextUpdate } from '../../components/ProgressToNextUpdate.js';\nimport { useRoutes } from '../../hooks/useRoutes.js';\nimport { useRouteExecutionStoreContext } from '../../stores/routes/RouteExecutionStore.js';\nimport { useSetExecutableRoute } from '../../stores/routes/useSetExecutableRoute.js';\n\nexport interface RouteTrackerProps {\n observableRouteId: string;\n onChange: Dispatch>;\n onFetching: Dispatch>;\n}\n\nexport const RouteTracker = ({\n observableRouteId,\n onChange,\n onFetching,\n}: RouteTrackerProps) => {\n const routeExecutionStore = useRouteExecutionStoreContext();\n const setExecutableRoute = useSetExecutableRoute();\n const [observableRoute] = useState(\n () => routeExecutionStore.getState().routes[observableRouteId]?.route,\n );\n const observableRouteIdRef = useRef(observableRoute?.id);\n const { routes, isFetching, dataUpdatedAt, refetchTime, refetch } = useRoutes(\n { observableRoute },\n );\n const currentRoute = routes?.[0];\n\n /**\n * The reviewable route is the route that the user currently sees on the review page.\n * The observable route is the route for which we track bridges and exchanges.\n * This allows us to query the route using the same tool each time we refresh.\n * The observable and reviewable routes can be the same when we first enter the review page.\n */\n useEffect(() => {\n if (\n observableRouteIdRef.current &&\n currentRoute &&\n observableRouteIdRef.current !== currentRoute.id\n ) {\n const reviewableRouteId = observableRouteIdRef.current;\n observableRouteIdRef.current = currentRoute.id;\n setExecutableRoute(currentRoute, [observableRouteId, reviewableRouteId]);\n onChange(currentRoute.id);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [currentRoute?.id, observableRouteId]);\n\n useEffect(() => {\n onFetching(isFetching);\n }, [isFetching, onFetching]);\n\n const handleRefetch = () => {\n refetch();\n };\n\n return (\n \n );\n};\n","import { BaseTransactionButton } from '../../components/BaseTransactionButton/BaseTransactionButton.js';\nimport { useFromTokenSufficiency } from '../../hooks/useFromTokenSufficiency.js';\nimport { useGasSufficiency } from '../../hooks/useGasSufficiency.js';\nimport type { StartTransactionButtonProps } from './types.js';\n\nexport const StartTransactionButton: React.FC = ({\n onClick,\n route,\n text,\n loading,\n}) => {\n const { insufficientGas, isLoading: isGasSufficiencyLoading } =\n useGasSufficiency(route);\n const { insufficientFromToken, isLoading: isFromTokenSufficiencyLoading } =\n useFromTokenSufficiency(route);\n\n const shouldDisableButton =\n insufficientFromToken || !!insufficientGas?.length;\n\n return (\n \n );\n};\n","import {\n Done,\n ErrorRounded,\n InfoRounded,\n WarningRounded,\n} from '@mui/icons-material';\nimport { Box, Button, Skeleton, Typography } from '@mui/material';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useEffect, useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { BottomSheet } from '../../components/BottomSheet/BottomSheet.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { Token } from '../../components/Token/Token.js';\nimport { useAvailableChains } from '../../hooks/useAvailableChains.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { getProcessMessage } from '../../hooks/useProcessMessage.js';\nimport { useSetContentHeight } from '../../hooks/useSetContentHeight.js';\nimport { useTokenBalance } from '../../hooks/useTokenBalance.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport {\n RouteExecutionStatus,\n type RouteExecution,\n} from '../../stores/routes/types.js';\nimport { getSourceTxHash } from '../../stores/routes/utils.js';\nimport { hasEnumFlag } from '../../utils/enum.js';\nimport { formatTokenAmount } from '../../utils/format.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport {\n CenterContainer,\n IconCircle,\n MessageSkeletonContainer,\n} from './StatusBottomSheet.style.js';\n\ninterface StatusBottomSheetContentProps extends RouteExecution {\n onClose(): void;\n}\n\nconst MessageSkeleton = () => (\n \n \n \n \n);\n\nexport const StatusBottomSheet: React.FC = ({\n status,\n route,\n}) => {\n const ref = useRef(null);\n\n const onClose = useCallback(() => {\n ref.current?.close();\n }, []);\n\n useEffect(() => {\n const hasSuccessFlag = hasEnumFlag(status, RouteExecutionStatus.Done);\n const hasFailedFlag = hasEnumFlag(status, RouteExecutionStatus.Failed);\n if ((hasSuccessFlag || hasFailedFlag) && !ref.current?.isOpen()) {\n ref.current?.open();\n }\n }, [status]);\n\n return (\n \n \n \n );\n};\n\nexport const StatusBottomSheetContent: React.FC<\n StatusBottomSheetContentProps\n> = ({ status, route, onClose }) => {\n const { t } = useTranslation();\n const { navigateBack, navigate } = useNavigateBack();\n const queryClient = useQueryClient();\n const { setFieldValue } = useFieldActions();\n const {\n subvariant,\n subvariantOptions,\n contractSecondaryComponent,\n contractCompactComponent,\n feeConfig,\n } = useWidgetConfig();\n const { getChainById } = useAvailableChains();\n\n const ref = useRef();\n useSetContentHeight(ref);\n\n const toToken = {\n ...(route.steps.at(-1)?.execution?.toToken ?? route.toToken),\n amount: BigInt(\n route.steps.at(-1)?.execution?.toAmount ??\n route.steps.at(-1)?.estimate.toAmount ??\n route.toAmount,\n ),\n };\n\n const toChain = getChainById(toToken.chainId);\n\n const { token, refetch, refetchNewBalance, refetchAllBalances } =\n useTokenBalance(route.toAddress, toToken, toChain);\n\n const invalidateQueries = () => {\n refetchAllBalances();\n setFieldValue('fromAmount', '');\n setFieldValue('toAmount', '');\n queryClient.invalidateQueries({ queryKey: ['transaction-history'] });\n };\n\n const handleDone = () => {\n invalidateQueries();\n navigateBack();\n };\n\n const handlePartialDone = () => {\n invalidateQueries();\n if (\n toToken.chainId !== route.toToken.chainId &&\n toToken.address !== route.toToken.address\n ) {\n setFieldValue(\n 'fromAmount',\n formatTokenAmount(toToken.amount, toToken.decimals),\n { isTouched: true },\n );\n setFieldValue('fromChain', toToken.chainId, { isTouched: true });\n setFieldValue('fromToken', toToken.address, { isTouched: true });\n setFieldValue('toChain', route.toToken.chainId, {\n isTouched: true,\n });\n setFieldValue('toToken', route.toToken.address, {\n isTouched: true,\n });\n }\n navigateBack();\n };\n\n const handleClose = () => {\n invalidateQueries();\n onClose();\n };\n\n const handleSeeDetails = () => {\n handleClose();\n\n const transactionHash = getSourceTxHash(route);\n\n navigate(navigationRoutes.transactionDetails, {\n state: {\n routeId: route.id,\n transactionHash,\n },\n replace: true,\n });\n };\n\n const transactionType =\n route.fromChainId === route.toChainId ? 'swap' : 'bridge';\n\n let title: string | undefined;\n let primaryMessage;\n let secondaryMessage;\n let handlePrimaryButton = handleDone;\n switch (status) {\n case RouteExecutionStatus.Done: {\n title =\n subvariant === 'custom'\n ? t(\n `success.title.${subvariantOptions?.custom ?? 'checkout'}Successful`,\n )\n : t(`success.title.${transactionType}Successful`);\n if (token) {\n primaryMessage = t('success.message.exchangeSuccessful', {\n amount: formatTokenAmount(token.amount, token.decimals),\n tokenSymbol: token.symbol,\n chainName: toChain?.name,\n walletAddress: shortenAddress(route.toAddress),\n });\n }\n handlePrimaryButton = handleDone;\n break;\n }\n case RouteExecutionStatus.Done | RouteExecutionStatus.Partial: {\n title = t(`success.title.${transactionType}PartiallySuccessful`);\n primaryMessage = t('success.message.exchangePartiallySuccessful', {\n tool: route.steps.at(-1)?.toolDetails.name,\n tokenSymbol: route.steps.at(-1)?.action.toToken.symbol,\n });\n if (token) {\n secondaryMessage = t('success.message.exchangeSuccessful', {\n amount: formatTokenAmount(token.amount, token.decimals),\n tokenSymbol: token.symbol,\n chainName: toChain?.name,\n walletAddress: shortenAddress(route.toAddress),\n });\n }\n handlePrimaryButton = handlePartialDone;\n break;\n }\n case RouteExecutionStatus.Done | RouteExecutionStatus.Refunded: {\n title = t('success.title.refundIssued');\n primaryMessage = t('success.message.exchangePartiallySuccessful', {\n tool: route.steps.at(-1)?.toolDetails.name,\n tokenSymbol: route.steps.at(-1)?.action.toToken.symbol,\n });\n if (token) {\n secondaryMessage = t('success.message.exchangeSuccessful', {\n amount: formatTokenAmount(token.amount, token.decimals),\n tokenSymbol: token.symbol,\n chainName: toChain?.name,\n walletAddress: shortenAddress(route.toAddress),\n });\n }\n break;\n }\n case RouteExecutionStatus.Failed: {\n const step = route.steps.find(\n (step) => step.execution?.status === 'FAILED',\n );\n const process = step?.execution?.process.find(\n (process) => process.status === 'FAILED',\n );\n if (!step || !process) {\n break;\n }\n const processMessage = getProcessMessage(t, getChainById, step, process);\n title = processMessage.title;\n primaryMessage = processMessage.message;\n handlePrimaryButton = handleClose;\n break;\n }\n default:\n break;\n }\n\n useEffect(() => {\n const hasSuccessFlag = hasEnumFlag(status, RouteExecutionStatus.Done);\n if (hasSuccessFlag) {\n refetchNewBalance();\n refetch();\n }\n }, [refetch, refetchNewBalance, status]);\n\n const showContractComponent =\n subvariant === 'custom' &&\n hasEnumFlag(status, RouteExecutionStatus.Done) &&\n (contractCompactComponent || contractSecondaryComponent);\n\n const VcComponent =\n status === RouteExecutionStatus.Done ? feeConfig?._vcComponent : undefined;\n\n return (\n \n {!showContractComponent ? (\n \n \n {status === RouteExecutionStatus.Idle ? (\n \n ) : null}\n {status === RouteExecutionStatus.Done ? (\n \n ) : null}\n {hasEnumFlag(status, RouteExecutionStatus.Partial) ||\n hasEnumFlag(status, RouteExecutionStatus.Refunded) ? (\n \n ) : null}\n {hasEnumFlag(status, RouteExecutionStatus.Failed) ? (\n \n ) : null}\n \n \n ) : null}\n \n \n {title}\n \n \n {showContractComponent ? (\n contractCompactComponent || contractSecondaryComponent\n ) : (\n \n {hasEnumFlag(status, RouteExecutionStatus.Done) ? (\n \n ) : null}\n \n )}\n {!showContractComponent ? (\n primaryMessage ? (\n {primaryMessage}\n ) : (\n \n )\n ) : null}\n {secondaryMessage ? (\n {secondaryMessage}\n ) : null}\n {VcComponent ? : null}\n \n {hasEnumFlag(status, RouteExecutionStatus.Done) ? (\n \n ) : null}\n \n \n \n );\n};\n","export const calculateValueLossPercentage = (\n fromAmountUSD: number,\n toAmountUSD: number,\n gasCostUSD: number,\n feeCostUSD: number,\n) => {\n return parseFloat(\n (\n (toAmountUSD / (fromAmountUSD + gasCostUSD + feeCostUSD) - 1) *\n 100\n ).toFixed(2),\n );\n};\n\nexport const getTokenValueLossThreshold = (\n fromAmountUSD: number,\n toAmountUSD: number,\n gasCostUSD: number,\n feeCostUSD: number,\n) => {\n if (!fromAmountUSD || !toAmountUSD) {\n return false;\n }\n return toAmountUSD / (fromAmountUSD + gasCostUSD + feeCostUSD) < 0.9;\n};\n","import type { Route } from '@lifi/sdk';\nimport { WarningRounded } from '@mui/icons-material';\nimport { Box, Button, Typography } from '@mui/material';\nimport type { MutableRefObject } from 'react';\nimport { forwardRef, useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { BottomSheet } from '../../components/BottomSheet/BottomSheet.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { FeeBreakdownTooltip } from '../../components/FeeBreakdownTooltip.js';\nimport { useSetContentHeight } from '../../hooks/useSetContentHeight.js';\nimport { getAccumulatedFeeCostsBreakdown } from '../../utils/fees.js';\nimport { CenterContainer, IconCircle } from './StatusBottomSheet.style.js';\nimport { calculateValueLossPercentage } from './utils.js';\n\ninterface TokenValueBottomSheetProps {\n route: Route;\n onContinue(): void;\n onCancel?(): void;\n}\n\nexport const TokenValueBottomSheet = forwardRef<\n BottomSheetBase,\n TokenValueBottomSheetProps\n>(({ route, onContinue, onCancel }, ref) => {\n const handleCancel = () => {\n (ref as MutableRefObject).current?.close();\n onCancel?.();\n };\n\n return (\n \n \n \n );\n});\n\nconst TokenValueBottomSheetContent: React.FC = ({\n route,\n onCancel,\n onContinue,\n}) => {\n const { t } = useTranslation();\n const ref = useRef();\n useSetContentHeight(ref);\n const { gasCosts, feeCosts, gasCostUSD, feeCostUSD } =\n getAccumulatedFeeCostsBreakdown(route);\n const fromAmountUSD = parseFloat(route.fromAmountUSD);\n const toAmountUSD = parseFloat(route.toAmountUSD);\n return (\n \n \n \n \n \n \n {t('warning.title.highValueLoss')}\n \n \n {t('warning.message.highValueLoss')}\n \n {t('main.sending')}\n \n {t('format.currency', { value: route.fromAmountUSD })}\n \n \n \n {t('main.fees.network')}\n \n \n {t('format.currency', { value: gasCostUSD })}\n \n \n \n {feeCostUSD ? (\n \n {t('main.fees.provider')}\n \n \n {t('format.currency', { value: feeCostUSD })}\n \n \n \n ) : null}\n \n {t('main.receiving')}\n \n {t('format.currency', { value: route.toAmountUSD })}\n \n \n \n {t('main.valueLoss')}\n \n {calculateValueLossPercentage(\n fromAmountUSD,\n toAmountUSD,\n gasCostUSD,\n feeCostUSD,\n )}\n %\n \n \n \n \n \n \n \n \n );\n};\n","import type { RouteObject } from 'react-router-dom';\nimport { useLocation, useRoutes } from 'react-router-dom';\nimport { NotFound } from './components/NotFound.js';\nimport { ActiveTransactionsPage } from './pages/ActiveTransactionsPage/ActiveTransactionsPage.js';\nimport { LanguagesPage } from './pages/LanguagesPage.js';\nimport { MainPage } from './pages/MainPage/MainPage.js';\nimport { RoutesPage } from './pages/RoutesPage/RoutesPage.js';\nimport { SelectChainPage } from './pages/SelectChainPage/SelectChainPage.js';\nimport { SelectEnabledToolsPage } from './pages/SelectEnabledToolsPage.js';\nimport { SelectTokenPage } from './pages/SelectTokenPage/SelectTokenPage.js';\nimport { SelectWalletPage } from './pages/SelectWalletPage/SelectWalletPage.js';\nimport { BookmarksPage } from './pages/SendToWallet/BookmarksPage.js';\nimport { ConnectedWalletsPage } from './pages/SendToWallet/ConnectedWalletsPage.js';\nimport { RecentWalletsPage } from './pages/SendToWallet/RecentWalletsPage.js';\nimport { SendToConfiguredWalletPage } from './pages/SendToWallet/SendToConfiguredWalletPage.js';\nimport { SendToWalletPage } from './pages/SendToWallet/SendToWalletPage.js';\nimport { SettingsPage } from './pages/SettingsPage/SettingsPage.js';\nimport { TransactionDetailsPage } from './pages/TransactionDetailsPage/TransactionDetailsPage.js';\nimport { TransactionHistoryPage } from './pages/TransactionHistoryPage/TransactionHistoryPage.js';\nimport { TransactionPage } from './pages/TransactionPage/TransactionPage.js';\nimport { navigationRoutes } from './utils/navigationRoutes.js';\n\n// SelectWalletPage should be accessible from every page and this handler helps avoid creating multiple paths.\n// Avoid using it for anything else, we need to come up with a better solution once we have one more page accessible from everywhere.\nconst NotFoundRouteHandler = () => {\n const { pathname } = useLocation();\n return pathname.includes(navigationRoutes.selectWallet) ? (\n \n ) : (\n \n );\n};\n\nconst routes: RouteObject[] = [\n {\n path: '/',\n element: ,\n },\n {\n path: navigationRoutes.settings,\n element: ,\n },\n {\n path: `${navigationRoutes.settings}/${navigationRoutes.bridges}`,\n element: ,\n },\n {\n path: `${navigationRoutes.settings}/${navigationRoutes.exchanges}`,\n element: ,\n },\n {\n path: `${navigationRoutes.settings}/${navigationRoutes.languages}`,\n element: ,\n },\n {\n path: navigationRoutes.fromToken,\n element: ,\n },\n {\n path: navigationRoutes.toToken,\n element: ,\n },\n {\n path: navigationRoutes.toTokenNative,\n element: ,\n },\n {\n path: `${navigationRoutes.fromToken}?/${navigationRoutes.fromChain}`,\n element: ,\n },\n {\n path: `${navigationRoutes.toToken}?/${navigationRoutes.toChain}`,\n element: ,\n },\n {\n path: navigationRoutes.routes,\n element: ,\n },\n {\n path: navigationRoutes.activeTransactions,\n element: ,\n },\n {\n path: navigationRoutes.sendToWallet,\n element: ,\n },\n {\n path: `${navigationRoutes.sendToWallet}/${navigationRoutes.bookmarks}`,\n element: ,\n },\n {\n path: `${navigationRoutes.sendToWallet}/${navigationRoutes.recentWallets}`,\n element: ,\n },\n {\n path: `${navigationRoutes.sendToWallet}/${navigationRoutes.connectedWallets}`,\n element: ,\n },\n {\n path: navigationRoutes.configuredWallets,\n element: ,\n },\n {\n path: navigationRoutes.transactionHistory,\n element: ,\n },\n {\n path: `${navigationRoutes.transactionHistory}?/${navigationRoutes.routes}?/${navigationRoutes.transactionExecution}?/${navigationRoutes.transactionDetails}`,\n element: ,\n },\n {\n path: `${navigationRoutes.routes}?/${navigationRoutes.activeTransactions}?/${navigationRoutes.transactionExecution}`,\n element: ,\n },\n {\n path: '*',\n element: ,\n },\n];\n\nexport const AppRoutes = () => {\n const element = useRoutes(routes);\n return element;\n};\n","import { Box } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { ActiveTransactions } from '../../components/ActiveTransactions/ActiveTransactions.js';\nimport { AmountInput } from '../../components/AmountInput/AmountInput.js';\nimport { ContractComponent } from '../../components/ContractComponent/ContractComponent.js';\nimport { GasRefuelMessage } from '../../components/GasMessage/GasRefuelMessage.js';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { PoweredBy } from '../../components/PoweredBy/PoweredBy.js';\nimport { Routes } from '../../components/Routes/Routes.js';\nimport { SelectChainAndToken } from '../../components/SelectChainAndToken.js';\nimport { SendToWalletButton } from '../../components/SendToWallet/SendToWalletButton.js';\nimport { SendToWalletExpandButton } from '../../components/SendToWallet/SendToWalletExpandButton.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useWideVariant } from '../../hooks/useWideVariant.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport { MainMessages } from './MainMessages.js';\nimport { ReviewButton } from './ReviewButton.js';\n\nexport const MainPage: React.FC = () => {\n const { t } = useTranslation();\n const wideVariant = useWideVariant();\n const { subvariant, subvariantOptions, contractComponent, hiddenUI } =\n useWidgetConfig();\n const custom = subvariant === 'custom';\n const showPoweredBy = !hiddenUI?.includes(HiddenUI.PoweredBy);\n\n const title =\n subvariant === 'custom'\n ? t(`header.${subvariantOptions?.custom ?? 'checkout'}`)\n : subvariant === 'refuel'\n ? t(`header.gas`)\n : t(`header.exchange`);\n useHeader(title);\n\n return (\n \n \n {custom ? (\n \n {contractComponent}\n \n ) : null}\n \n {!custom ? (\n \n ) : null}\n {!wideVariant ? : null}\n \n \n \n \n \n \n \n {showPoweredBy ? : null}\n \n );\n};\n","import { useTranslation } from 'react-i18next';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { BridgeAndExchangeSettings } from './BridgeAndExchangeSettings.js';\nimport { GasPriceSettings } from './GasPriceSettings.js';\nimport { LanguageSetting } from './LanguageSetting.js';\nimport { ResetSettingsButton } from './ResetSettingsButton.js';\nimport { RoutePrioritySettings } from './RoutePrioritySettings.js';\nimport { SettingsList } from './SettingsCard/SettingCard.style.js';\nimport { SettingsCardAccordion } from './SettingsCard/SettingsAccordian.js';\nimport { SlippageSettings } from './SlippageSettings/SlippageSettings.js';\nimport { ThemeSettings } from './ThemeSettings.js';\n\nexport const SettingsPage = () => {\n const { t } = useTranslation();\n useHeader(t(`header.settings`));\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n};\n","import { Check } from '@mui/icons-material';\nimport { List } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { ListItemText } from '../components/ListItemText.js';\nimport { PageContainer } from '../components/PageContainer.js';\nimport { SettingsListItemButton } from '../components/SettingsListItemButton.js';\nimport { useHeader } from '../hooks/useHeader.js';\nimport { useLanguages } from '../hooks/useLanguages.js';\n\nexport const LanguagesPage: React.FC = () => {\n const { t } = useTranslation();\n const { selectedLanguageCode, availableLanguages, setLanguageWithCode } =\n useLanguages();\n\n useHeader(t(`language.title`));\n\n if (availableLanguages.length < 1) {\n return null;\n }\n\n return (\n \n \n {availableLanguages.map((language) => (\n setLanguageWithCode(language)}\n >\n \n {selectedLanguageCode === language && }\n \n ))}\n \n \n );\n};\n","/* eslint-disable react/no-array-index-key */\nimport type { Route } from '@lifi/sdk';\nimport type { BoxProps } from '@mui/material';\nimport { useMemo } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { ProgressToNextUpdate } from '../../components/ProgressToNextUpdate.js';\nimport { RouteCard } from '../../components/RouteCard/RouteCard.js';\nimport { RouteCardSkeleton } from '../../components/RouteCard/RouteCardSkeleton.js';\nimport { RouteNotFoundCard } from '../../components/RouteCard/RouteNotFoundCard.js';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useRoutes } from '../../hooks/useRoutes.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { Stack } from './RoutesPage.style.js';\n\nexport const RoutesPage: React.FC = () => {\n const { navigate } = useNavigateBack();\n const {\n routes,\n isLoading,\n isFetching,\n dataUpdatedAt,\n refetchTime,\n fromChain,\n refetch,\n setReviewableRoute,\n } = useRoutes();\n const { account } = useAccount({ chainType: fromChain?.chainType });\n const [toAddress] = useFieldValues('toAddress');\n const { requiredToAddress } = useToAddressRequirements();\n\n const { t } = useTranslation();\n\n const headerAction = useMemo(\n () => (\n refetch()}\n sx={{ marginRight: -1 }}\n size=\"medium\"\n />\n ),\n [dataUpdatedAt, isFetching, refetch, refetchTime],\n );\n\n useHeader(t(`header.receive`), headerAction);\n\n const handleRouteClick = (route: Route) => {\n setReviewableRoute(route);\n navigate(navigationRoutes.transactionExecution, {\n state: { routeId: route.id },\n });\n };\n\n const routeNotFound = !routes?.length && !isLoading && !isFetching;\n\n const toAddressUnsatisfied = routes?.[0] && requiredToAddress && !toAddress;\n const allowInteraction = account.isConnected && !toAddressUnsatisfied;\n\n return (\n \n {routeNotFound ? (\n \n ) : isLoading ? (\n Array.from({ length: 3 }).map((_, index) => (\n \n ))\n ) : (\n routes?.map((route: Route, index: number) => (\n handleRouteClick(route) : undefined\n }\n active={index === 0}\n expanded={routes?.length === 1}\n />\n ))\n )}\n \n );\n};\n","import { Error, History, TurnedIn, Wallet } from '@mui/icons-material';\nimport { Box, Tooltip, Typography } from '@mui/material';\nimport type { ChangeEvent } from 'react';\nimport { useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { ButtonTertiary } from '../../components/ButtonTertiary.js';\nimport { CardButton } from '../../components/Card/CardButton.js';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport {\n AddressType,\n useAddressValidation,\n} from '../../hooks/useAddressValidation.js';\nimport { useChain } from '../../hooks/useChain.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { Bookmark } from '../../stores/bookmarks/types.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useBookmarks } from '../../stores/bookmarks/useBookmarks.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { BookmarkAddressSheet } from './BookmarkAddressSheet.js';\nimport { ConfirmAddressSheet } from './ConfirmAddressSheet.js';\nimport {\n AddressInput,\n FullHeightAdjustablePageContainer,\n SendToWalletButtonRow,\n SendToWalletCard,\n SendToWalletIconButton,\n ValidationAlert,\n} from './SendToWalletPage.style.js';\n\nexport const SendToWalletPage = () => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const bookmarkAddressSheetRef = useRef(null);\n const confirmAddressSheetRef = useRef(null);\n const { bookmarks, recentWallets } = useBookmarks();\n const {\n addBookmark,\n getBookmark,\n setSelectedBookmark,\n getSelectedBookmark,\n addRecentWallet,\n } = useBookmarkActions();\n const { setFieldValue } = useFieldActions();\n const [inputAddressValue, setInputAddressValue] = useState(\n () => getSelectedBookmark()?.address ?? '',\n );\n const [validatedWallet, setValidatedWallet] = useState();\n const [errorMessage, setErrorMessage] = useState('');\n const { validateAddress, isValidating } = useAddressValidation();\n const { accounts } = useAccount();\n const connectedWallets = accounts.filter((account) => account.isConnected);\n const { requiredToChainType } = useToAddressRequirements();\n const [toChainId] = useFieldValues('toChain');\n const { chain: toChain } = useChain(toChainId);\n const [isDoneButtonLoading, setIsDoneButtonLoading] = useState(false);\n const [isBookmarkButtonLoading, setIsBookmarkButtonLoading] = useState(false);\n const { variant } = useWidgetConfig();\n\n useHeader(t(`header.sendToWallet`));\n\n const handleInputChange = (e: ChangeEvent) => {\n if (errorMessage) {\n setErrorMessage('');\n }\n if (getSelectedBookmark()) {\n setFieldValue('toAddress', '', { isTouched: true });\n setSelectedBookmark();\n }\n setInputAddressValue((e.target as HTMLInputElement).value.trim());\n };\n\n const handleDone = async () => {\n if (isValidating) {\n return;\n }\n if (!inputAddressValue) {\n setErrorMessage(t('error.title.walletAddressRequired'));\n return;\n }\n setIsDoneButtonLoading(true);\n const validationResult = await validateAddress({\n value: inputAddressValue,\n chainType: requiredToChainType,\n chain: toChain,\n });\n setIsDoneButtonLoading(false);\n if (!validationResult.isValid) {\n setErrorMessage(validationResult.error);\n return;\n }\n\n if (\n requiredToChainType &&\n requiredToChainType !== validationResult.chainType\n ) {\n setErrorMessage(\n t('error.title.walletChainTypeInvalid', {\n chainName: toChain?.name,\n }),\n );\n return;\n }\n\n setValidatedWallet({\n name:\n validationResult.addressType === AddressType.NameService\n ? inputAddressValue\n : undefined,\n address: validationResult.address,\n chainType: validationResult.chainType,\n });\n confirmAddressSheetRef.current?.open();\n };\n\n const handleBookmarkAddress = async () => {\n if (isValidating) {\n return;\n }\n if (!inputAddressValue) {\n setErrorMessage(t('error.title.walletAddressRequired'));\n return;\n }\n\n const existingBookmarkWallet = getBookmark(inputAddressValue);\n if (existingBookmarkWallet) {\n setErrorMessage(\n t('error.title.bookmarkAlreadyExists', {\n name: existingBookmarkWallet.name,\n }),\n );\n return;\n }\n setIsBookmarkButtonLoading(true);\n const validationResult = await validateAddress({\n value: inputAddressValue,\n });\n setIsBookmarkButtonLoading(false);\n\n if (validationResult.isValid) {\n setValidatedWallet({\n name:\n validationResult.addressType === AddressType.NameService\n ? inputAddressValue\n : undefined,\n address: validationResult.address,\n chainType: validationResult.chainType,\n });\n bookmarkAddressSheetRef.current?.open();\n } else {\n setErrorMessage(validationResult.error);\n }\n };\n\n const handleRecentWalletsClick = () => {\n navigate(navigationRoutes.recentWallets);\n };\n\n const handleConnectedWalletsClick = () => {\n navigate(navigationRoutes.connectedWallets);\n };\n const handleBookmarkedWalletsClick = () => {\n navigate(navigationRoutes.bookmarks);\n };\n\n const handleAddBookmark = (bookmark: Bookmark) => {\n addBookmark(bookmark);\n navigate(navigationRoutes.bookmarks);\n };\n\n const handleOnConfirm = (confirmedWallet: Bookmark) => {\n setSelectedBookmark(confirmedWallet);\n addRecentWallet(confirmedWallet);\n };\n\n const placeholder = t('sendToWallet.enterAddress', {\n context: 'long',\n });\n\n return (\n \n \n \n {errorMessage ? (\n } sx={{ pb: 2, paddingX: 2 }}>\n {errorMessage}\n \n ) : null}\n \n \n {t('button.done')}\n \n \n \n \n \n \n \n \n \n \n \n }\n onClick={handleRecentWalletsClick}\n >\n {!!recentWallets.length && (\n \n {recentWallets.length}\n \n )}\n \n }\n onClick={handleConnectedWalletsClick}\n >\n {!!connectedWallets.length && (\n \n {connectedWallets.length}\n \n )}\n \n }\n onClick={handleBookmarkedWalletsClick}\n >\n {!!bookmarks.length && (\n {bookmarks.length}\n )}\n \n \n \n );\n};\n","import {\n ContentCopyRounded,\n DeleteOutline,\n MoreHoriz,\n OpenInNewRounded,\n TurnedIn,\n} from '@mui/icons-material';\nimport { Button, ListItemAvatar, ListItemText, MenuItem } from '@mui/material';\nimport { useId, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\n\nimport { AccountAvatar } from '../../components/Avatar/AccountAvatar.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { ListItemButton } from '../../components/ListItem//ListItemButton.js';\nimport { ListItem } from '../../components/ListItem/ListItem.js';\nimport { Menu } from '../../components/Menu.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { Bookmark } from '../../stores/bookmarks/types.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useBookmarks } from '../../stores/bookmarks/useBookmarks.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport { defaultChainIdsByType } from '../../utils/chainType.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { BookmarkAddressSheet } from './BookmarkAddressSheet.js';\nimport { EmptyListIndicator } from './EmptyListIndicator.js';\nimport {\n BookmarkButtonContainer,\n BookmarksListContainer,\n FullHeightAdjustablePageContainer,\n OptionsMenuButton,\n} from './SendToWalletPage.style.js';\n\nexport const BookmarksPage = () => {\n const { t } = useTranslation();\n const [bookmark, setBookmark] = useState();\n const bookmarkAddressSheetRef = useRef(null);\n const { bookmarks } = useBookmarks();\n const { requiredToChainType } = useToAddressRequirements();\n const { addBookmark, removeBookmark, setSelectedBookmark } =\n useBookmarkActions();\n const navigate = useNavigate();\n const { setFieldValue } = useFieldActions();\n const { setSendToWallet } = useSendToWalletActions();\n const { variant } = useWidgetConfig();\n const { getAddressLink } = useExplorer();\n\n useHeader(t(`header.bookmarkedWallets`));\n\n const handleAddBookmark = () => {\n bookmarkAddressSheetRef.current?.open();\n };\n\n const handleBookmarkSelected = (bookmark: Bookmark) => {\n setFieldValue('toAddress', bookmark.address, {\n isTouched: true,\n });\n setSelectedBookmark(bookmark);\n setSendToWallet(true);\n navigate(`../../`, {\n relative: 'path',\n replace: true,\n });\n };\n\n const moreMenuId = useId();\n const [moreMenuAnchorEl, setMenuAnchorEl] = useState();\n const open = Boolean(moreMenuAnchorEl);\n const closeMenu = () => {\n setMenuAnchorEl(null);\n };\n\n const handleMenuOpen = (el: HTMLElement, bookmark: Bookmark) => {\n setMenuAnchorEl(el);\n setBookmark(bookmark);\n };\n\n const handleCopyAddress = () => {\n if (bookmark) {\n navigator.clipboard.writeText(bookmark.address);\n }\n closeMenu();\n };\n\n const handleViewOnExplorer = () => {\n if (bookmark) {\n window.open(\n getAddressLink(\n bookmark.address,\n defaultChainIdsByType[bookmark.chainType],\n ),\n '_blank',\n );\n }\n closeMenu();\n };\n\n const handleRemoveBookmark = () => {\n if (bookmark) {\n removeBookmark(bookmark.address);\n }\n closeMenu();\n };\n\n return (\n \n \n {bookmarks.map((bookmark) => (\n \n handleBookmarkSelected(bookmark)}\n disabled={\n requiredToChainType &&\n requiredToChainType !== bookmark.chainType\n }\n >\n \n \n \n \n \n handleMenuOpen(e.target as HTMLElement, bookmark)}\n sx={{\n opacity:\n requiredToChainType &&\n requiredToChainType !== bookmark.chainType\n ? 0.5\n : 1,\n }}\n >\n \n \n \n ))}\n {!bookmarks.length && (\n }>\n {t('sendToWallet.noBookmarkedWallets')}\n \n )}\n \n \n \n {t('button.copyAddress')}\n \n \n \n {t('button.viewOnExplorer')}\n \n \n \n {t('button.delete')}\n \n \n \n \n \n \n \n \n );\n};\n","import {\n ContentCopyRounded,\n DeleteOutline,\n MoreHoriz,\n OpenInNewRounded,\n TurnedInNot,\n Wallet,\n} from '@mui/icons-material';\nimport { ListItemAvatar, ListItemText, MenuItem } from '@mui/material';\nimport { useId, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { AccountAvatar } from '../../components/Avatar/AccountAvatar.js';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { ListItem } from '../../components/ListItem/ListItem.js';\nimport { ListItemButton } from '../../components/ListItem/ListItemButton.js';\nimport { Menu } from '../../components/Menu.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport type { Bookmark } from '../../stores/bookmarks/types.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useBookmarks } from '../../stores/bookmarks/useBookmarks.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport { defaultChainIdsByType } from '../../utils/chainType.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { BookmarkAddressSheet } from './BookmarkAddressSheet.js';\nimport { EmptyListIndicator } from './EmptyListIndicator.js';\nimport {\n ListContainer,\n OptionsMenuButton,\n SendToWalletPageContainer,\n} from './SendToWalletPage.style.js';\n\nexport const RecentWalletsPage = () => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const [selectedRecent, setSelectedRecent] = useState();\n const bookmarkAddressSheetRef = useRef(null);\n const { recentWallets } = useBookmarks();\n const { requiredToChainType } = useToAddressRequirements();\n const {\n removeRecentWallet,\n addBookmark,\n setSelectedBookmark,\n addRecentWallet,\n } = useBookmarkActions();\n const { setFieldValue } = useFieldActions();\n const { setSendToWallet } = useSendToWalletActions();\n const moreMenuId = useId();\n const [moreMenuAnchorEl, setMenuAnchorEl] = useState();\n const open = Boolean(moreMenuAnchorEl);\n const { getAddressLink } = useExplorer();\n\n useHeader(t(`header.recentWallets`));\n\n const handleRecentSelected = (recentWallet: Bookmark) => {\n addRecentWallet(recentWallet);\n setFieldValue('toAddress', recentWallet.address, {\n isTouched: true,\n });\n setSelectedBookmark(recentWallet);\n setSendToWallet(true);\n navigate(`../../`, {\n relative: 'path',\n replace: true,\n });\n };\n\n const handleAddBookmark = (bookmark: Bookmark) => {\n addBookmark(bookmark);\n navigate(`../${navigationRoutes.bookmarks}`, {\n relative: 'path',\n replace: true,\n });\n };\n\n const closeMenu = () => {\n setMenuAnchorEl(null);\n };\n\n const handleMenuOpen = (el: HTMLElement, recentWallet: Bookmark) => {\n setMenuAnchorEl(el);\n setSelectedRecent(recentWallet);\n };\n\n const handleCopyAddress = () => {\n if (selectedRecent) {\n navigator.clipboard.writeText(selectedRecent.address);\n }\n closeMenu();\n };\n\n const handleViewOnExplorer = () => {\n if (selectedRecent) {\n window.open(\n getAddressLink(\n selectedRecent.address,\n defaultChainIdsByType[selectedRecent.chainType],\n ),\n '_blank',\n );\n }\n closeMenu();\n };\n\n const handleOpenBookmarkSheet = () => {\n if (selectedRecent) {\n setSelectedRecent(selectedRecent);\n bookmarkAddressSheetRef.current?.open();\n }\n closeMenu();\n };\n\n const handleRemoveRecentWallet = () => {\n if (selectedRecent) {\n removeRecentWallet(selectedRecent.address);\n }\n closeMenu();\n };\n\n return (\n \n \n {recentWallets.map((recentWallet) => (\n \n handleRecentSelected(recentWallet)}\n >\n \n \n \n \n \n \n handleMenuOpen(e.target as HTMLElement, recentWallet)\n }\n sx={{\n opacity:\n requiredToChainType &&\n requiredToChainType !== recentWallet.chainType\n ? 0.5\n : 1,\n }}\n >\n \n \n \n ))}\n {!recentWallets.length && (\n }>\n {t('sendToWallet.noRecentWallets')}\n \n )}\n \n \n \n {t('button.copyAddress')}\n \n \n \n {t('button.viewOnExplorer')}\n \n \n \n {t('button.bookmark')}\n \n \n \n {t('button.delete')}\n \n \n \n \n \n );\n};\n","import {\n ContentCopyRounded,\n MoreHoriz,\n OpenInNewRounded,\n TurnedIn,\n} from '@mui/icons-material';\nimport { ListItemAvatar, ListItemText, MenuItem } from '@mui/material';\nimport { useId, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigate } from 'react-router-dom';\nimport { AccountAvatar } from '../../components/Avatar/AccountAvatar.js';\nimport { ListItem } from '../../components/ListItem/ListItem.js';\nimport { ListItemButton } from '../../components/ListItem/ListItemButton.js';\nimport { Menu } from '../../components/Menu.js';\nimport type { Account } from '../../hooks/useAccount.js';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { EmptyListIndicator } from './EmptyListIndicator.js';\nimport {\n ListContainer,\n OptionsMenuButton,\n SendToWalletPageContainer,\n} from './SendToWalletPage.style.js';\n\nexport const ConnectedWalletsPage = () => {\n const { t } = useTranslation();\n const [selectedAccount, setSelectedAccount] = useState();\n const { accounts } = useAccount();\n const { setSelectedBookmark } = useBookmarkActions();\n const { requiredToChainType } = useToAddressRequirements();\n const navigate = useNavigate();\n const { setFieldValue } = useFieldActions();\n const { setSendToWallet } = useSendToWalletActions();\n const [moreMenuAnchorEl, setMenuAnchorEl] = useState();\n const moreMenuId = useId();\n const open = Boolean(moreMenuAnchorEl);\n const { getAddressLink } = useExplorer();\n\n useHeader(t('sendToWallet.connectedWallets'));\n\n const handleWalletSelected = (account: Account) => {\n setFieldValue('toAddress', account.address!, {\n isTouched: true,\n });\n setSelectedBookmark({\n name: account.connector?.name,\n address: account.address!,\n chainType: account.chainType!,\n isConnectedAccount: true,\n });\n setSendToWallet(true);\n navigate(`../../`, {\n relative: 'path',\n replace: true,\n });\n };\n\n const closeMenu = () => {\n setMenuAnchorEl(null);\n };\n\n const handleMenuOpen = (el: HTMLElement, connectedWallet: Account) => {\n setMenuAnchorEl(el);\n setSelectedAccount(connectedWallet);\n };\n\n const handleCopyAddress = () => {\n if (selectedAccount?.address) {\n navigator.clipboard.writeText(selectedAccount.address);\n }\n closeMenu();\n };\n\n const handleViewOnExplorer = () => {\n if (selectedAccount?.chainId) {\n if (selectedAccount.address) {\n window.open(\n getAddressLink(selectedAccount.address, selectedAccount.chainId),\n '_blank',\n );\n }\n }\n closeMenu();\n };\n\n return (\n \n \n {accounts.map((account) => {\n const walletAddress = shortenAddress(account.address);\n\n return (\n \n handleWalletSelected(account)}\n disabled={\n requiredToChainType &&\n requiredToChainType !== account.chainType\n }\n >\n \n \n \n \n \n \n handleMenuOpen(e.target as HTMLElement, account)\n }\n sx={{\n opacity:\n requiredToChainType &&\n requiredToChainType !== account.chainType\n ? 0.5\n : 1,\n }}\n >\n \n \n \n );\n })}\n {!accounts.length && (\n }>\n {t('sendToWallet.noConnectedWallets')}\n \n )}\n \n \n \n {t('button.copyAddress')}\n \n \n \n {t('button.viewOnExplorer')}\n \n \n \n \n );\n};\n","import {\n ContentCopyRounded,\n MoreHoriz,\n OpenInNewRounded,\n} from '@mui/icons-material';\nimport { ListItemAvatar, ListItemText, MenuItem } from '@mui/material';\nimport { useId, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { AccountAvatar } from '../../components/Avatar/AccountAvatar.js';\nimport { ListItem } from '../../components/ListItem/ListItem.js';\nimport { ListItemButton } from '../../components/ListItem/ListItemButton.js';\nimport { Menu } from '../../components/Menu.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport type { ToAddress } from '../../types/widget.js';\nimport { defaultChainIdsByType } from '../../utils/chainType.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport {\n ListContainer,\n OptionsMenuButton,\n SendToWalletPageContainer,\n} from './SendToWalletPage.style.js';\n\nexport const SendToConfiguredWalletPage = () => {\n const { t } = useTranslation();\n const { navigateBack } = useNavigateBack();\n const { toAddresses } = useWidgetConfig();\n const [selectedToAddress, setSelectedToAddress] = useState();\n const { requiredToChainType } = useToAddressRequirements();\n const { setSelectedBookmark } = useBookmarkActions();\n const { setFieldValue } = useFieldActions();\n const moreMenuId = useId();\n const [moreMenuAnchorEl, setMenuAnchorEl] = useState();\n const open = Boolean(moreMenuAnchorEl);\n const { getAddressLink } = useExplorer();\n\n useHeader(t(`header.sendToWallet`));\n\n const handleCuratedSelected = (toAddress: ToAddress) => {\n setSelectedBookmark(toAddress);\n setFieldValue('toAddress', toAddress.address, { isTouched: true });\n navigateBack();\n };\n\n const closeMenu = () => {\n setMenuAnchorEl(null);\n };\n\n const handleMenuOpen = (el: HTMLElement, toAddress: ToAddress) => {\n setMenuAnchorEl(el);\n setSelectedToAddress(toAddress);\n };\n\n const handleCopyAddress = () => {\n if (selectedToAddress) {\n navigator.clipboard.writeText(selectedToAddress.address);\n }\n closeMenu();\n };\n\n const handleViewOnExplorer = () => {\n if (selectedToAddress) {\n window.open(\n getAddressLink(\n selectedToAddress.address,\n defaultChainIdsByType[selectedToAddress.chainType],\n ),\n '_blank',\n );\n }\n closeMenu();\n };\n\n return (\n \n \n {toAddresses?.map((toAddress) => (\n \n handleCuratedSelected(toAddress)}\n >\n \n \n \n \n \n \n handleMenuOpen(e.target as HTMLElement, toAddress)\n }\n sx={{\n opacity:\n requiredToChainType &&\n requiredToChainType !== toAddress.chainType\n ? 0.5\n : 1,\n }}\n >\n \n \n \n ))}\n \n \n \n {t('button.copyAddress')}\n \n \n \n {t('button.viewOnExplorer')}\n \n \n \n \n );\n};\n","import type { FullStatusData } from '@lifi/sdk';\nimport { List } from '@mui/material';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport { useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useTransactionHistory } from '../../hooks/useTransactionHistory.js';\nimport { TransactionHistoryEmpty } from './TransactionHistoryEmpty.js';\nimport { TransactionHistoryItem } from './TransactionHistoryItem.js';\nimport { TransactionHistoryItemSkeleton } from './TransactionHistorySkeleton.js';\nimport { minTransactionListHeight } from './constants.js';\n\nexport const TransactionHistoryPage: React.FC = () => {\n // Parent ref and useVirtualizer should be in one file to avoid blank page (0 virtual items) issue\n const parentRef = useRef(null);\n const { data: transactions, isLoading } = useTransactionHistory();\n\n const { t } = useTranslation();\n useHeader(t(`header.transactionHistory`));\n\n const { getVirtualItems, getTotalSize } = useVirtualizer({\n count: transactions.length,\n overscan: 10,\n paddingEnd: 12,\n getScrollElement: () => parentRef.current,\n estimateSize: () => 186,\n getItemKey: (index) =>\n `${(transactions[index] as FullStatusData).transactionId}-${index}`,\n });\n\n if (!transactions.length && !isLoading) {\n return ;\n }\n\n return (\n \n {isLoading ? (\n \n {Array.from({ length: 3 }).map((_, index) => (\n \n ))}\n \n ) : (\n \n {getVirtualItems().map((item) => {\n const transaction = transactions[item.index];\n return (\n \n );\n })}\n \n )}\n \n );\n};\n","export const minTransactionListHeight = 544;\n","import type { FullStatusData } from '@lifi/sdk';\nimport { Box, Typography } from '@mui/material';\nimport { useEffect, useMemo } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useLocation } from 'react-router-dom';\nimport { ContractComponent } from '../../components/ContractComponent/ContractComponent.js';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { getStepList } from '../../components/Step/StepList.js';\nimport { TransactionDetails } from '../../components/TransactionDetails.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useTools } from '../../hooks/useTools.js';\nimport { useTransactionDetails } from '../../hooks/useTransactionDetails.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useRouteExecutionStore } from '../../stores/routes/RouteExecutionStore.js';\nimport { getSourceTxHash } from '../../stores/routes/utils.js';\nimport { buildRouteFromTxHistory } from '../../utils/converters.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { ContactSupportButton } from './ContactSupportButton.js';\nimport { TransactionDetailsSkeleton } from './TransactionDetailsSkeleton.js';\nimport { TransferIdCard } from './TransferIdCard.js';\n\nexport const TransactionDetailsPage: React.FC = () => {\n const { t, i18n } = useTranslation();\n const { navigate } = useNavigateBack();\n const { subvariant, subvariantOptions, contractSecondaryComponent } =\n useWidgetConfig();\n const { state }: any = useLocation();\n const { tools } = useTools();\n const storedRouteExecution = useRouteExecutionStore(\n (store) => store.routes[state?.routeId],\n );\n\n const { transaction, isLoading } = useTransactionDetails(\n !storedRouteExecution && state?.transactionHash,\n );\n\n const title =\n subvariant === 'custom'\n ? t(`header.${subvariantOptions?.custom ?? 'checkout'}Details`)\n : t(`header.transactionDetails`);\n useHeader(title);\n\n const routeExecution = useMemo(() => {\n if (storedRouteExecution) {\n return storedRouteExecution;\n }\n if (isLoading) {\n return;\n }\n if (transaction) {\n const routeExecution = buildRouteFromTxHistory(\n transaction as FullStatusData,\n tools,\n );\n return routeExecution;\n }\n }, [isLoading, storedRouteExecution, tools, transaction]);\n\n useEffect(() => {\n if (!isLoading && !routeExecution) {\n navigate(navigationRoutes.home);\n }\n }, [isLoading, navigate, routeExecution]);\n\n const sourceTxHash = getSourceTxHash(routeExecution?.route);\n\n let supportId = sourceTxHash ?? routeExecution?.route.id ?? '';\n\n if (process.env.NODE_ENV === 'development') {\n supportId += `_${routeExecution?.route.id}`;\n }\n\n const startedAt = new Date(\n (routeExecution?.route.steps[0].execution?.process[0].startedAt ?? 0) *\n (storedRouteExecution ? 1 : 1000), // local and BE routes have different ms handling\n );\n\n return isLoading && !storedRouteExecution ? (\n \n ) : (\n \n \n \n {startedAt.toLocaleString(i18n.language, {\n dateStyle: 'long',\n })}\n \n \n {startedAt.toLocaleString(i18n.language, {\n timeStyle: 'short',\n })}\n \n \n {getStepList(routeExecution?.route, subvariant)}\n {subvariant === 'custom' && contractSecondaryComponent ? (\n \n {contractSecondaryComponent}\n \n ) : null}\n {routeExecution?.route ? (\n \n ) : null}\n \n \n \n \n \n );\n};\n","import type { FullStatusData } from '@lifi/sdk';\nimport { getStatus, type StatusResponse } from '@lifi/sdk';\nimport {\n keepPreviousData,\n useQuery,\n useQueryClient,\n} from '@tanstack/react-query';\nimport { useAccount } from './useAccount.js';\n\nexport const useTransactionDetails = (transactionHash?: string) => {\n const { account, accounts } = useAccount();\n const queryClient = useQueryClient();\n\n const { data, isLoading } = useQuery({\n queryKey: ['transaction-history', transactionHash],\n queryFn: async ({ queryKey: [, transactionHash], signal }) => {\n if (transactionHash) {\n for (const account of accounts) {\n const cachedHistory = queryClient.getQueryData([\n 'transaction-history',\n account.address,\n ]);\n\n const transaction = cachedHistory?.find(\n (t) => t.sending.txHash === transactionHash,\n );\n\n if (transaction) {\n return transaction;\n }\n }\n\n const transaction = await getStatus(\n {\n txHash: transactionHash,\n },\n { signal },\n );\n\n const fromAddress = (transaction as FullStatusData)?.fromAddress;\n\n if (fromAddress) {\n queryClient.setQueryData(\n ['transaction-history', fromAddress],\n (data) => {\n return [...data!, transaction!];\n },\n );\n }\n\n return transaction;\n }\n },\n refetchInterval: 300_000,\n enabled: account.isConnected && Boolean(transactionHash),\n initialData: () => {\n for (const account of accounts) {\n const transaction = queryClient\n .getQueryData<\n StatusResponse[]\n >(['transaction-history', account.address])\n ?.find((t) => t.sending.txHash === transactionHash);\n if (transaction) {\n return transaction;\n }\n }\n },\n placeholderData: keepPreviousData,\n });\n\n return {\n transaction: data,\n isLoading,\n };\n};\n","import type { ExchangeRateUpdateParams } from '@lifi/sdk';\nimport { Delete } from '@mui/icons-material';\nimport { Box, Button, Tooltip } from '@mui/material';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useLocation } from 'react-router-dom';\nimport type { BottomSheetBase } from '../../components/BottomSheet/types.js';\nimport { ContractComponent } from '../../components/ContractComponent/ContractComponent.js';\nimport { GasMessage } from '../../components/GasMessage/GasMessage.js';\nimport { PageContainer } from '../../components/PageContainer.js';\nimport { getStepList } from '../../components/Step/StepList.js';\nimport { TransactionDetails } from '../../components/TransactionDetails.js';\nimport { useHeader } from '../../hooks/useHeader.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useRouteExecution } from '../../hooks/useRouteExecution.js';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { RouteExecutionStatus } from '../../stores/routes/types.js';\nimport { WidgetEvent } from '../../types/events.js';\nimport { getAccumulatedFeeCostsBreakdown } from '../../utils/fees.js';\nimport type { ExchangeRateBottomSheetBase } from './ExchangeRateBottomSheet.js';\nimport { ExchangeRateBottomSheet } from './ExchangeRateBottomSheet.js';\nimport { RouteTracker } from './RouteTracker.js';\nimport { StartTransactionButton } from './StartTransactionButton.js';\nimport { StatusBottomSheet } from './StatusBottomSheet.js';\nimport { TokenValueBottomSheet } from './TokenValueBottomSheet.js';\nimport {\n calculateValueLossPercentage,\n getTokenValueLossThreshold,\n} from './utils.js';\n\nexport const TransactionPage: React.FC = () => {\n const { t } = useTranslation();\n const { setFieldValue } = useFieldActions();\n const emitter = useWidgetEvents();\n const { navigateBack } = useNavigateBack();\n const { subvariant, subvariantOptions, contractSecondaryComponent } =\n useWidgetConfig();\n const { state }: any = useLocation();\n const stateRouteId = state?.routeId;\n const [routeId, setRouteId] = useState(stateRouteId);\n const [routeRefreshing, setRouteRefreshing] = useState(false);\n\n const tokenValueBottomSheetRef = useRef(null);\n const exchangeRateBottomSheetRef = useRef(null);\n\n const onAcceptExchangeRateUpdate = (\n resolver: (value: boolean) => void,\n data: ExchangeRateUpdateParams,\n ) => {\n exchangeRateBottomSheetRef.current?.open(resolver, data);\n };\n\n const { route, status, executeRoute, restartRoute, deleteRoute } =\n useRouteExecution({\n routeId: routeId,\n onAcceptExchangeRateUpdate,\n });\n\n const getHeaderTitle = () => {\n if (subvariant === 'custom') {\n return t(`header.${subvariantOptions?.custom ?? 'checkout'}`);\n } else {\n if (route) {\n const transactionType =\n route.fromChainId === route.toChainId ? 'swap' : 'bridge';\n return status === RouteExecutionStatus.Idle\n ? t(`button.${transactionType}Review`)\n : t(`header.${transactionType}`);\n }\n }\n\n return t(`header.exchange`);\n };\n\n const headerAction = useMemo(\n () =>\n status === RouteExecutionStatus.Idle ? (\n \n ) : undefined,\n [stateRouteId, status],\n );\n\n useHeader(getHeaderTitle(), headerAction);\n\n useEffect(() => {\n if (status === RouteExecutionStatus.Idle) {\n emitter.emit(WidgetEvent.ReviewTransactionPageEntered, route);\n }\n // We want to emit event only when the page is mounted\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (!route) {\n return null;\n }\n\n const handleExecuteRoute = () => {\n if (tokenValueBottomSheetRef.current?.isOpen()) {\n const { gasCostUSD, feeCostUSD } = getAccumulatedFeeCostsBreakdown(route);\n const fromAmountUSD = parseFloat(route.fromAmountUSD);\n const toAmountUSD = parseFloat(route.toAmountUSD);\n emitter.emit(WidgetEvent.RouteHighValueLoss, {\n fromAmountUSD,\n toAmountUSD,\n gasCostUSD,\n feeCostUSD,\n valueLoss: calculateValueLossPercentage(\n fromAmountUSD,\n toAmountUSD,\n gasCostUSD,\n feeCostUSD,\n ),\n });\n }\n tokenValueBottomSheetRef.current?.close();\n executeRoute();\n setFieldValue('fromAmount', '');\n if (subvariant === 'custom') {\n setFieldValue('fromToken', '');\n setFieldValue('toToken', '');\n }\n };\n\n const handleStartClick = async () => {\n if (status === RouteExecutionStatus.Idle) {\n const { gasCostUSD, feeCostUSD } = getAccumulatedFeeCostsBreakdown(route);\n const fromAmountUSD = parseFloat(route.fromAmountUSD);\n const toAmountUSD = parseFloat(route.toAmountUSD);\n const tokenValueLossThresholdExceeded = getTokenValueLossThreshold(\n fromAmountUSD,\n toAmountUSD,\n gasCostUSD,\n feeCostUSD,\n );\n if (tokenValueLossThresholdExceeded && subvariant !== 'custom') {\n tokenValueBottomSheetRef.current?.open();\n } else {\n handleExecuteRoute();\n }\n }\n if (status === RouteExecutionStatus.Failed) {\n restartRoute();\n }\n };\n\n const handleRemoveRoute = () => {\n navigateBack();\n deleteRoute();\n };\n\n const getButtonText = (): string => {\n switch (status) {\n case RouteExecutionStatus.Idle:\n switch (subvariant) {\n case 'custom':\n return subvariantOptions?.custom === 'deposit'\n ? t(`button.deposit`)\n : t(`button.buy`);\n case 'refuel':\n return t('button.startBridging');\n default:\n const transactionType =\n route.fromChainId === route.toChainId ? 'Swapping' : 'Bridging';\n return t(`button.start${transactionType}`);\n }\n case RouteExecutionStatus.Failed:\n return t('button.tryAgain');\n default:\n return '';\n }\n };\n\n return (\n \n {getStepList(route, subvariant)}\n {subvariant === 'custom' && contractSecondaryComponent ? (\n \n {contractSecondaryComponent}\n \n ) : null}\n \n {status === RouteExecutionStatus.Idle ||\n status === RouteExecutionStatus.Failed ? (\n <>\n \n \n \n {status === RouteExecutionStatus.Failed ? (\n \n \n \n \n \n ) : null}\n \n \n ) : null}\n {status ? : null}\n {subvariant !== 'custom' ? (\n \n ) : null}\n \n \n );\n};\n","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport GlobalStyles from '../GlobalStyles';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nexport const html = (theme, enableColorScheme) => _extends({\n WebkitFontSmoothing: 'antialiased',\n // Antialiasing.\n MozOsxFontSmoothing: 'grayscale',\n // Antialiasing.\n // Change from `box-sizing: content-box` so that `width`\n // is not affected by `padding` or `border`.\n boxSizing: 'border-box',\n // Fix font resize problem in iOS\n WebkitTextSizeAdjust: '100%'\n}, enableColorScheme && !theme.vars && {\n colorScheme: theme.palette.mode\n});\nexport const body = theme => _extends({\n color: (theme.vars || theme).palette.text.primary\n}, theme.typography.body1, {\n backgroundColor: (theme.vars || theme).palette.background.default,\n '@media print': {\n // Save printer ink.\n backgroundColor: (theme.vars || theme).palette.common.white\n }\n});\nexport const styles = (theme, enableColorScheme = false) => {\n var _theme$components;\n const colorSchemeStyles = {};\n if (enableColorScheme && theme.colorSchemes) {\n Object.entries(theme.colorSchemes).forEach(([key, scheme]) => {\n var _scheme$palette;\n colorSchemeStyles[theme.getColorSchemeSelector(key).replace(/\\s*&/, '')] = {\n colorScheme: (_scheme$palette = scheme.palette) == null ? void 0 : _scheme$palette.mode\n };\n });\n }\n let defaultStyles = _extends({\n html: html(theme, enableColorScheme),\n '*, *::before, *::after': {\n boxSizing: 'inherit'\n },\n 'strong, b': {\n fontWeight: theme.typography.fontWeightBold\n },\n body: _extends({\n margin: 0\n }, body(theme), {\n // Add support for document.body.requestFullScreen().\n // Other elements, if background transparent, are not supported.\n '&::backdrop': {\n backgroundColor: (theme.vars || theme).palette.background.default\n }\n })\n }, colorSchemeStyles);\n const themeOverrides = (_theme$components = theme.components) == null || (_theme$components = _theme$components.MuiCssBaseline) == null ? void 0 : _theme$components.styleOverrides;\n if (themeOverrides) {\n defaultStyles = [defaultStyles, themeOverrides];\n }\n return defaultStyles;\n};\n\n/**\n * Kickstart an elegant, consistent, and simple baseline to build upon.\n */\nfunction CssBaseline(inProps) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCssBaseline'\n });\n const {\n children,\n enableColorScheme = false\n } = props;\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [/*#__PURE__*/_jsx(GlobalStyles, {\n styles: theme => styles(theme, enableColorScheme)\n }), children]\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? CssBaseline.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * You can wrap a node.\n */\n children: PropTypes.node,\n /**\n * Enable `color-scheme` CSS property to use `theme.palette.mode`.\n * For more details, check out https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme\n * For browser support, check out https://caniuse.com/?search=color-scheme\n * @default false\n */\n enableColorScheme: PropTypes.bool\n} : void 0;\nexport default CssBaseline;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getScopedCssBaselineUtilityClass(slot) {\n return generateUtilityClass('MuiScopedCssBaseline', slot);\n}\nconst scopedCssBaselineClasses = generateUtilityClasses('MuiScopedCssBaseline', ['root']);\nexport default scopedCssBaselineClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\", \"component\", \"enableColorScheme\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport styled from '../styles/styled';\nimport { html, body } from '../CssBaseline/CssBaseline';\nimport { getScopedCssBaselineUtilityClass } from './scopedCssBaselineClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root']\n };\n return composeClasses(slots, getScopedCssBaselineUtilityClass, classes);\n};\nconst ScopedCssBaselineRoot = styled('div', {\n name: 'MuiScopedCssBaseline',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})(({\n theme,\n ownerState\n}) => {\n const colorSchemeStyles = {};\n if (ownerState.enableColorScheme && theme.colorSchemes) {\n Object.entries(theme.colorSchemes).forEach(([key, scheme]) => {\n var _scheme$palette;\n colorSchemeStyles[`&${theme.getColorSchemeSelector(key).replace(/\\s*&/, '')}`] = {\n colorScheme: (_scheme$palette = scheme.palette) == null ? void 0 : _scheme$palette.mode\n };\n });\n }\n return _extends({}, html(theme, ownerState.enableColorScheme), body(theme), {\n '& *, & *::before, & *::after': {\n boxSizing: 'inherit'\n },\n '& strong, & b': {\n fontWeight: theme.typography.fontWeightBold\n }\n }, colorSchemeStyles);\n});\nconst ScopedCssBaseline = /*#__PURE__*/React.forwardRef(function ScopedCssBaseline(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiScopedCssBaseline'\n });\n const {\n className,\n component = 'div'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n component\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(ScopedCssBaselineRoot, _extends({\n as: component,\n className: clsx(classes.root, className),\n ref: ref,\n ownerState: ownerState\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? ScopedCssBaseline.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * Enable `color-scheme` CSS property to use `theme.palette.mode`.\n * For more details, check out https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme\n * For browser support, check out https://caniuse.com/?search=color-scheme\n */\n enableColorScheme: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default ScopedCssBaseline;","import { Box, Container, ScopedCssBaseline, styled } from '@mui/material';\nimport type { PropsWithChildren } from 'react';\nimport { defaultMaxHeight } from '../config/constants.js';\nimport { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js';\nimport { useHeaderHeight } from '../stores/header/useHeaderStore.js';\nimport type { WidgetVariant } from '../types/widget.js';\nimport { ElementId, createElementId } from '../utils/elements.js';\n\n// NOTE: the setting of the height in AppExpandedContainer, RelativeContainer and CssBaselineContainer can\n// be done dynamically by values in the config - namely the config.theme.container values display, maxHeight and height\n// A Number of other components and hooks work with height values that are often set on or derived from these elements\n// if there are changes to how the height works here you should also check the functionality of these hooks and their point of use\n// - useTokenListHeight\n// - useSetContentHeight\n// Also check any code that is using the methods from elements.ts utils file\n\nexport const AppExpandedContainer = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'variant',\n})<{ variant?: WidgetVariant }>(({ theme, variant }) => ({\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'start',\n flex: 1,\n height:\n variant === 'drawer'\n ? 'none'\n : theme.container?.display === 'flex'\n ? '100%'\n : theme.container?.maxHeight\n ? 'auto'\n : theme.container?.height || 'auto',\n}));\n\nexport const RelativeContainer = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'variant',\n})<{ variant?: WidgetVariant }>(({ theme, variant }) => {\n const container = { ...theme.container };\n\n if (variant === 'drawer') {\n container.height = '100%';\n }\n\n return {\n position: 'relative',\n boxSizing: 'content-box',\n width: '100%',\n minWidth: theme.breakpoints.values.xs,\n maxWidth: theme.breakpoints.values.sm,\n background: theme.palette.background.default,\n overflow: 'auto',\n flex: 1,\n zIndex: 0,\n ...container,\n maxHeight:\n variant === 'drawer'\n ? 'none'\n : theme.container?.display === 'flex' && !theme.container?.height\n ? '100%'\n : theme.container?.maxHeight\n ? theme.container?.maxHeight\n : theme.container?.height || defaultMaxHeight,\n };\n});\n\ninterface CssBaselineContainerProps {\n variant?: WidgetVariant;\n paddingTopAdjustment: number;\n elementId: string;\n}\n\nconst CssBaselineContainer = styled(ScopedCssBaseline, {\n shouldForwardProp: (prop) =>\n !['variant', 'paddingTopAdjustment', 'elementId'].includes(prop as string),\n})(\n ({ theme, variant, paddingTopAdjustment, elementId }) => ({\n display: 'flex',\n flex: 1,\n flexDirection: 'column',\n overflowX: 'clip',\n margin: 0,\n width: '100%',\n maxHeight:\n variant === 'drawer' || theme.container?.display === 'flex'\n ? 'none'\n : theme.container?.maxHeight\n ? theme.container?.maxHeight\n : theme.container?.height || defaultMaxHeight,\n overflowY: 'auto',\n height: theme.container?.display === 'flex' ? 'auto' : '100%',\n paddingTop: paddingTopAdjustment,\n // This allows FullPageContainer.tsx to expand and fill the available vertical space in max height and default layout modes\n [`&:has(.full-page-container)`]: {\n height: theme.container?.maxHeight\n ? theme.container?.maxHeight\n : theme.container?.height || defaultMaxHeight,\n },\n }),\n);\n\nexport const FlexContainer = styled(Container)(({ theme }) => ({\n display: 'flex',\n flexDirection: 'column',\n flex: 1,\n}));\n\nexport const AppContainer: React.FC> = ({ children }) => {\n // const ref = useRef(null);\n const { variant, elementId, theme } = useWidgetConfig();\n const { headerHeight } = useHeaderHeight();\n const positionFixedAdjustment =\n theme?.header?.position === 'fixed' ? headerHeight : 0;\n\n return (\n \n \n {children}\n \n {/* */}\n \n );\n};\n\n// export const ScrollToLocation: React.FC<{\n// elementRef: RefObject;\n// }> = ({ elementRef }) => {\n// const { pathname } = useLocation();\n// useLayoutEffect(() => {\n// elementRef.current?.scrollTo(0, 0);\n// }, [elementRef, pathname]);\n// return null;\n// };\n","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getAppBarUtilityClass(slot) {\n return generateUtilityClass('MuiAppBar', slot);\n}\nconst appBarClasses = generateUtilityClasses('MuiAppBar', ['root', 'positionFixed', 'positionAbsolute', 'positionSticky', 'positionStatic', 'positionRelative', 'colorDefault', 'colorPrimary', 'colorSecondary', 'colorInherit', 'colorTransparent', 'colorError', 'colorInfo', 'colorSuccess', 'colorWarning']);\nexport default appBarClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nconst _excluded = [\"className\", \"color\", \"enableColorOnDark\", \"position\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport styled from '../styles/styled';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport capitalize from '../utils/capitalize';\nimport Paper from '../Paper';\nimport { getAppBarUtilityClass } from './appBarClasses';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n color,\n position,\n classes\n } = ownerState;\n const slots = {\n root: ['root', `color${capitalize(color)}`, `position${capitalize(position)}`]\n };\n return composeClasses(slots, getAppBarUtilityClass, classes);\n};\n\n// var2 is the fallback.\n// Ex. var1: 'var(--a)', var2: 'var(--b)'; return: 'var(--a, var(--b))'\nconst joinVars = (var1, var2) => var1 ? `${var1 == null ? void 0 : var1.replace(')', '')}, ${var2})` : var2;\nconst AppBarRoot = styled(Paper, {\n name: 'MuiAppBar',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[`position${capitalize(ownerState.position)}`], styles[`color${capitalize(ownerState.color)}`]];\n }\n})(({\n theme,\n ownerState\n}) => {\n const backgroundColorDefault = theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[900];\n return _extends({\n display: 'flex',\n flexDirection: 'column',\n width: '100%',\n boxSizing: 'border-box',\n // Prevent padding issue with the Modal and fixed positioned AppBar.\n flexShrink: 0\n }, ownerState.position === 'fixed' && {\n position: 'fixed',\n zIndex: (theme.vars || theme).zIndex.appBar,\n top: 0,\n left: 'auto',\n right: 0,\n '@media print': {\n // Prevent the app bar to be visible on each printed page.\n position: 'absolute'\n }\n }, ownerState.position === 'absolute' && {\n position: 'absolute',\n zIndex: (theme.vars || theme).zIndex.appBar,\n top: 0,\n left: 'auto',\n right: 0\n }, ownerState.position === 'sticky' && {\n // ⚠️ sticky is not supported by IE11.\n position: 'sticky',\n zIndex: (theme.vars || theme).zIndex.appBar,\n top: 0,\n left: 'auto',\n right: 0\n }, ownerState.position === 'static' && {\n position: 'static'\n }, ownerState.position === 'relative' && {\n position: 'relative'\n }, !theme.vars && _extends({}, ownerState.color === 'default' && {\n backgroundColor: backgroundColorDefault,\n color: theme.palette.getContrastText(backgroundColorDefault)\n }, ownerState.color && ownerState.color !== 'default' && ownerState.color !== 'inherit' && ownerState.color !== 'transparent' && {\n backgroundColor: theme.palette[ownerState.color].main,\n color: theme.palette[ownerState.color].contrastText\n }, ownerState.color === 'inherit' && {\n color: 'inherit'\n }, theme.palette.mode === 'dark' && !ownerState.enableColorOnDark && {\n backgroundColor: null,\n color: null\n }, ownerState.color === 'transparent' && _extends({\n backgroundColor: 'transparent',\n color: 'inherit'\n }, theme.palette.mode === 'dark' && {\n backgroundImage: 'none'\n })), theme.vars && _extends({}, ownerState.color === 'default' && {\n '--AppBar-background': ownerState.enableColorOnDark ? theme.vars.palette.AppBar.defaultBg : joinVars(theme.vars.palette.AppBar.darkBg, theme.vars.palette.AppBar.defaultBg),\n '--AppBar-color': ownerState.enableColorOnDark ? theme.vars.palette.text.primary : joinVars(theme.vars.palette.AppBar.darkColor, theme.vars.palette.text.primary)\n }, ownerState.color && !ownerState.color.match(/^(default|inherit|transparent)$/) && {\n '--AppBar-background': ownerState.enableColorOnDark ? theme.vars.palette[ownerState.color].main : joinVars(theme.vars.palette.AppBar.darkBg, theme.vars.palette[ownerState.color].main),\n '--AppBar-color': ownerState.enableColorOnDark ? theme.vars.palette[ownerState.color].contrastText : joinVars(theme.vars.palette.AppBar.darkColor, theme.vars.palette[ownerState.color].contrastText)\n }, !['inherit', 'transparent'].includes(ownerState.color) && {\n backgroundColor: 'var(--AppBar-background)'\n }, {\n color: ownerState.color === 'inherit' ? 'inherit' : 'var(--AppBar-color)'\n }, ownerState.color === 'transparent' && {\n backgroundImage: 'none',\n backgroundColor: 'transparent',\n color: 'inherit'\n }));\n});\nconst AppBar = /*#__PURE__*/React.forwardRef(function AppBar(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiAppBar'\n });\n const {\n className,\n color = 'primary',\n enableColorOnDark = false,\n position = 'fixed'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n color,\n position,\n enableColorOnDark\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(AppBarRoot, _extends({\n square: true,\n component: \"header\",\n ownerState: ownerState,\n elevation: 4,\n className: clsx(classes.root, className, position === 'fixed' && 'mui-fixed'),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? AppBar.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'primary'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary', 'transparent', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * If true, the `color` prop is applied in dark mode.\n * @default false\n */\n enableColorOnDark: PropTypes.bool,\n /**\n * The positioning type. The behavior of the different options is described\n * [in the MDN web docs](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning).\n * Note: `sticky` is not universally supported and will fall back to `static` when unavailable.\n * @default 'fixed'\n */\n position: PropTypes.oneOf(['absolute', 'fixed', 'relative', 'static', 'sticky']),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default AppBar;","import {\n AppBar,\n Avatar,\n Box,\n Button,\n buttonClasses,\n styled,\n} from '@mui/material';\nimport type { WidgetSubvariant } from '../../types/widget.js';\nimport { getContrastAlphaColor } from '../../utils/colors.js';\nimport { avatarMask12 } from '../Avatar/utils.js';\n\nexport const HeaderAppBar = styled(AppBar)(({ theme }) => ({\n backgroundColor: 'transparent',\n color: theme.palette.text.primary,\n flexDirection: 'row',\n alignItems: 'center',\n position: 'relative',\n}));\n\nexport const Container = styled(Box, {\n shouldForwardProp: (prop) => prop !== 'sticky',\n})<{ sticky?: boolean }>(({ theme, sticky }) => {\n return {\n display: 'flex',\n flexDirection: 'column',\n backgroundColor: theme.palette.background.default,\n backdropFilter: 'blur(12px)',\n position: sticky ? 'sticky' : 'relative',\n top: 0,\n zIndex: 1200,\n gap: theme.spacing(0.5),\n padding: theme.spacing(1.5, 3, 1.5, 3),\n overflow: 'auto',\n ...theme.header,\n ...(theme.header?.position === 'fixed'\n ? {\n minWidth: theme.breakpoints.values.xs,\n maxWidth: theme.breakpoints.values.sm,\n width: '100%',\n }\n : {}),\n };\n});\n\nexport const WalletButton = styled(Button, {\n shouldForwardProp: (prop) => prop !== 'subvariant',\n})<{ subvariant?: WidgetSubvariant }>(({ subvariant, theme }) => ({\n color: theme.palette.text.primary,\n backgroundColor: 'transparent',\n padding: theme.spacing(1, 1.5),\n maxHeight: 40,\n fontSize: '0.875rem',\n fontWeight: 600,\n borderRadius: theme.shape.borderRadius * 2,\n '&:hover': {\n backgroundColor: getContrastAlphaColor(theme, 0.04),\n },\n [`.${buttonClasses.endIcon} > *:nth-of-type(1)`]: {\n fontSize: '24px',\n },\n [`.${buttonClasses.startIcon} > *:nth-of-type(1)`]: {\n fontSize: '24px',\n },\n ...(theme.navigation.edge && {\n marginRight: subvariant === 'split' ? 0 : theme.spacing(-1.25),\n marginLeft: subvariant === 'split' ? theme.spacing(-1) : 0,\n }),\n}));\n\nexport const DrawerWalletContainer = styled(Box)(({ theme }) => ({\n width: '100%',\n display: 'flex',\n justifyContent: 'space-between',\n\n ...(theme.navigation.edge && {\n '& button:first-of-type': {\n marginLeft: theme.spacing(-1),\n },\n '& button:last-of-type': {\n marginRight: theme.spacing(-1.25),\n },\n }),\n}));\n\nexport const HeaderControlsContainer = styled(Box)(({ theme }) => ({\n display: 'flex',\n gap: theme.spacing(0.5),\n ...(theme.navigation.edge && {\n '& button:last-of-type': {\n marginRight: theme.spacing(-1.25),\n },\n }),\n}));\n\nexport const WalletAvatar = styled(Avatar)(({ theme }) => ({\n mask: avatarMask12,\n width: 24,\n height: 24,\n}));\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z\"\n}), 'ArrowBack');","import { ArrowBack } from '@mui/icons-material';\nimport type { IconButtonProps } from '@mui/material';\nimport { IconButton, useTheme } from '@mui/material';\n\nexport const BackButton: React.FC = ({ onClick }) => {\n const theme = useTheme();\n\n return (\n \n \n \n );\n};\n","import { createContext, useContext } from 'react';\n\nexport interface WidgetDrawerContext {\n closeDrawer?(): void;\n}\n\nexport const DrawerContext = createContext({});\n\nexport const useDrawer = (): WidgetDrawerContext => useContext(DrawerContext);\n","import { CloseRounded } from '@mui/icons-material';\nimport { IconButton, Tooltip } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useDrawer } from '../../AppDrawerContext.js';\nimport { useHasExternalWalletProvider } from '../../providers/WalletProvider/useHasExternalWalletProvider.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\n\ninterface CloseDrawerButtonProps {\n header?: 'navigation' | 'wallet';\n}\n\nexport const CloseDrawerButton = ({ header }: CloseDrawerButtonProps) => {\n const { t } = useTranslation();\n const { subvariant } = useWidgetConfig();\n const { closeDrawer } = useDrawer();\n const { hasExternalProvider } = useHasExternalWalletProvider();\n\n const showInNavigationHeader =\n header === 'navigation' && (hasExternalProvider || subvariant === 'split');\n\n const showInWalletHeader = header === 'wallet' && subvariant !== 'split';\n\n return showInNavigationHeader || showInWalletHeader ? (\n \n \n \n \n \n ) : null;\n};\n","import { useTranslation } from 'react-i18next';\nimport { useFieldActions } from '../../stores/form/useFieldActions.js';\nimport { useSplitSubvariantStore } from '../../stores/settings/useSplitSubvariantStore.js';\nimport { Tab, Tabs } from '../Tabs/Tabs.style.js';\nimport { HeaderAppBar } from './Header.style.js';\n\nexport const NavigationTabs = () => {\n const { t } = useTranslation();\n const [state, setState] = useSplitSubvariantStore((state) => [\n state.state,\n state.setState,\n ]);\n\n const { setFieldValue } = useFieldActions();\n const handleChange = (_: React.SyntheticEvent, value: number) => {\n setFieldValue('fromAmount', '');\n setFieldValue('fromToken', '');\n setFieldValue('toToken', '');\n setState(value === 0 ? 'swap' : 'bridge');\n };\n\n return (\n \n \n \n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6\"\n}), 'Settings');","import {\n IconButton,\n Badge as MuiBadge,\n badgeClasses,\n darken,\n styled,\n} from '@mui/material';\nimport {\n getInfoBackgroundColor,\n getWarningBackgroundColor,\n} from '../../utils/colors.js';\n\nexport const SettingsIconBadge = styled(MuiBadge)(({ theme }) => ({\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(1.25),\n [`.${badgeClasses.badge}`]: {\n width: 10,\n height: 10,\n borderRadius: '50%',\n transform: 'translate(70%, -70%)',\n },\n}));\n\ninterface SettingsIconButtonProps {\n variant?: 'info' | 'warning';\n}\n\nexport const SettingsIconButton = styled(IconButton, {\n shouldForwardProp: (props) => props !== 'variant',\n})(({ theme, variant }) => {\n switch (variant) {\n case 'info':\n return {\n backgroundColor: getInfoBackgroundColor(theme),\n '&:hover': {\n backgroundColor: darken(getInfoBackgroundColor(theme), 0.2),\n },\n };\n case 'warning':\n return {\n backgroundColor: getWarningBackgroundColor(theme),\n '&:hover': {\n backgroundColor: darken(getWarningBackgroundColor(theme), 0.2),\n },\n };\n default:\n break;\n }\n});\n","import { Settings } from '@mui/icons-material';\nimport { Tooltip } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useSettingMonitor } from '../../hooks/useSettingMonitor.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport {\n SettingsIconBadge,\n SettingsIconButton,\n} from './SettingsButton.style.js';\n\nexport const SettingsButton = () => {\n const { t } = useTranslation();\n const { navigate } = useNavigateBack();\n\n const { isCustomRouteSettings, isRouteSettingsWithWarnings } =\n useSettingMonitor();\n\n const variant = isRouteSettingsWithWarnings\n ? 'warning'\n : isCustomRouteSettings\n ? 'info'\n : undefined;\n\n const tooltipMessage = variant\n ? t(`tooltip.settingsModified`)\n : t(`header.settings`);\n\n return (\n \n navigate(navigationRoutes.settings)}\n variant={variant}\n >\n {variant ? (\n \n \n \n ) : (\n \n )}\n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon([/*#__PURE__*/_jsx(\"path\", {\n d: \"M19.5 3.5 18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2v14H3v3c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V2zM19 19c0 .55-.45 1-1 1s-1-.45-1-1v-3H8V5h11z\"\n}, \"0\"), /*#__PURE__*/_jsx(\"path\", {\n d: \"M9 7h6v2H9zm7 0h2v2h-2zm-7 3h6v2H9zm7 0h2v2h-2z\"\n}, \"1\")], 'ReceiptLong');","import { ReceiptLong } from '@mui/icons-material';\nimport { IconButton, Tooltip } from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\n\nexport const TransactionHistoryButton = () => {\n const { t } = useTranslation();\n const { navigate } = useNavigateBack();\n\n return (\n \n navigate(navigationRoutes.transactionHistory)}\n >\n \n \n \n );\n};\n","\"use client\";\n\nimport createSvgIcon from './utils/createSvgIcon';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon( /*#__PURE__*/_jsx(\"path\", {\n d: \"M12 3c-.55 0-1 .45-1 1v8c0 .55.45 1 1 1s1-.45 1-1V4c0-.55-.45-1-1-1m5.14 2.86c-.39.39-.38 1-.01 1.39 1.13 1.2 1.83 2.8 1.87 4.57.09 3.83-3.08 7.13-6.91 7.17C8.18 19.05 5 15.9 5 12c0-1.84.71-3.51 1.87-4.76.37-.39.37-1-.01-1.38-.4-.4-1.05-.39-1.43.02C3.98 7.42 3.07 9.47 3 11.74c-.14 4.88 3.83 9.1 8.71 9.25 5.1.16 9.29-3.93 9.29-9 0-2.37-.92-4.51-2.42-6.11-.38-.41-1.04-.42-1.44-.02\"\n}), 'PowerSettingsNewRounded');","import { PowerSettingsNewRounded } from '@mui/icons-material';\nimport { IconButton } from '@mui/material';\nimport type { Connector } from 'wagmi';\nimport { useDisconnect } from 'wagmi';\n\nexport const EVMDisconnectIconButton = ({\n connector,\n}: {\n connector?: Connector;\n}) => {\n const { disconnect } = useDisconnect();\n\n return (\n {\n e.stopPropagation();\n disconnect({ connector });\n }}\n >\n \n \n );\n};\n","import { PowerSettingsNewRounded } from '@mui/icons-material';\nimport { IconButton } from '@mui/material';\nimport { useWallet } from '@solana/wallet-adapter-react';\n\nexport const SVMDisconnectIconButton = () => {\n const { disconnect } = useWallet();\n\n return (\n {\n e.stopPropagation();\n disconnect();\n }}\n >\n \n \n );\n};\n","import { ChainType } from '@lifi/sdk';\nimport { getConnectorIcon } from '@lifi/wallet-management';\nimport {\n ContentCopyRounded,\n OpenInNewRounded,\n PowerSettingsNewRounded,\n} from '@mui/icons-material';\nimport {\n Avatar,\n Badge,\n Box,\n Button,\n IconButton,\n MenuItem,\n} from '@mui/material';\nimport { useTranslation } from 'react-i18next';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useAvailableChains } from '../../hooks/useAvailableChains.js';\nimport { useExplorer } from '../../hooks/useExplorer.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { AvatarMasked } from '../Avatar/Avatar.style.js';\nimport { SmallAvatar } from '../SmallAvatar.js';\nimport { EVMDisconnectIconButton } from './EVMDisconnectIconButton.js';\nimport { SVMDisconnectIconButton } from './SVMDisconnectIconButton.js';\n\nexport const WalletMenu = ({ onClose }: { onClose: () => void }) => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { pathname } = useLocation();\n const { accounts } = useAccount();\n const { getChainById } = useAvailableChains();\n const connect = async () => {\n navigate(navigationRoutes.selectWallet);\n onClose();\n };\n const { getAddressLink } = useExplorer();\n\n return (\n <>\n \n {accounts.map((account) => {\n const chain = getChainById(account.chainId);\n const walletAddress = shortenAddress(account.address);\n const handleCopyAddress = async () => {\n await navigator.clipboard.writeText(account.address ?? '');\n onClose();\n };\n\n return (\n \n \n {chain?.logoURI ? (\n \n {chain?.name[0]}\n \n }\n sx={{ marginRight: 1.5 }}\n >\n \n {account.connector?.name[0]}\n \n \n ) : (\n \n {account.connector?.name[0]}\n \n )}\n {walletAddress}\n \n \n \n \n \n \n \n \n {account.chainType === ChainType.EVM ? (\n \n ) : account.chainType === ChainType.SVM ? (\n \n ) : null}\n \n \n );\n })}\n \n {!pathname.includes(navigationRoutes.selectWallet) ? (\n }\n sx={{\n marginTop: 1,\n }}\n >\n {accounts.length > 1\n ? t(`button.changeWallet`)\n : t(`button.connectWallet`)}\n \n ) : null}\n \n );\n};\n","import {\n Menu as MuiMenu,\n menuClasses,\n menuItemClasses,\n styled,\n svgIconClasses,\n} from '@mui/material';\n\nexport const WalletMenuContainer = styled(MuiMenu)(({ theme }) => ({\n [`& .${menuClasses.paper}`]: {\n borderRadius: theme.shape.borderRadius,\n color: theme.palette.text.primary,\n boxShadow: '0px 2px 4px rgb(0 0 0 / 8%), 0px 8px 16px rgb(0 0 0 / 8%)',\n padding: theme.spacing(2),\n [`& .${menuClasses.list}`]: {\n padding: 0,\n },\n [`& .${menuItemClasses.root}`]: {\n borderRadius: theme.shape.borderRadiusSecondary,\n padding: theme.spacing(1, 2, 1, 1),\n [`& .${svgIconClasses.root}`]: {\n fontSize: 20,\n color: theme.palette.text.primary,\n },\n },\n },\n}));\n","import { getConnectorIcon } from '@lifi/wallet-management';\nimport { ExpandMore, Wallet } from '@mui/icons-material';\nimport { Avatar, Badge } from '@mui/material';\nimport { useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport type { Account } from '../../hooks/useAccount.js';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useChain } from '../../hooks/useChain.js';\nimport { useHasExternalWalletProvider } from '../../providers/WalletProvider/useHasExternalWalletProvider.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { shortenAddress } from '../../utils/wallet.js';\nimport { SmallAvatar } from '../SmallAvatar.js';\nimport { CloseDrawerButton } from './CloseDrawerButton.js';\nimport {\n DrawerWalletContainer,\n HeaderAppBar,\n WalletAvatar,\n WalletButton,\n} from './Header.style.js';\nimport { WalletMenu } from './WalletMenu.js';\nimport { WalletMenuContainer } from './WalletMenu.style.js';\n\nexport const WalletHeader: React.FC = () => {\n const { subvariant, hiddenUI } = useWidgetConfig();\n const { hasExternalProvider } = useHasExternalWalletProvider();\n return !hasExternalProvider &&\n subvariant !== 'split' &&\n !hiddenUI?.includes(HiddenUI.WalletMenu) ? (\n \n \n \n ) : null;\n};\n\nexport const SplitWalletMenuButton: React.FC = () => {\n const { hiddenUI } = useWidgetConfig();\n const { hasExternalProvider } = useHasExternalWalletProvider();\n return !hasExternalProvider && !hiddenUI?.includes(HiddenUI.WalletMenu) ? (\n \n ) : null;\n};\n\nexport const WalletMenuButton: React.FC = () => {\n const { account } = useAccount();\n const { variant, hiddenUI } = useWidgetConfig();\n\n if (variant === 'drawer') {\n return (\n \n {account.isConnected ? (\n \n ) : (\n \n )}\n {!hiddenUI?.includes(HiddenUI.DrawerCloseButton) ? (\n \n ) : null}\n \n );\n }\n return account.isConnected ? (\n \n ) : (\n \n );\n};\n\nconst ConnectButton = () => {\n const { t } = useTranslation();\n const { pathname } = useLocation();\n const { walletConfig, subvariant, variant } = useWidgetConfig();\n const navigate = useNavigate();\n const connect = async () => {\n if (walletConfig?.onConnect) {\n walletConfig.onConnect();\n return;\n }\n navigate(navigationRoutes.selectWallet);\n };\n return (\n : undefined\n }\n startIcon={\n variant === 'drawer' || subvariant === 'split' ? (\n \n ) : undefined\n }\n onClick={\n !pathname.includes(navigationRoutes.selectWallet) ? connect : undefined\n }\n >\n {t(`button.connectWallet`)}\n \n );\n};\n\nconst ConnectedButton = ({ account }: { account: Account }) => {\n const { subvariant } = useWidgetConfig();\n const { chain } = useChain(account.chainId);\n const [anchorEl, setAnchorEl] = useState(null);\n const walletAddress = shortenAddress(account.address);\n\n const handleClick = (event: React.MouseEvent) => {\n setAnchorEl(event.currentTarget);\n };\n\n const handleClose = () => {\n setAnchorEl(null);\n };\n\n return (\n <>\n }\n startIcon={\n chain?.logoURI ? (\n \n {chain?.name[0]}\n \n }\n >\n \n {account.connector?.name[0]}\n \n \n ) : (\n \n {account.connector?.name[0]}\n \n )\n }\n onClick={handleClick}\n >\n {walletAddress}\n \n \n \n \n \n );\n};\n","import { Box, Typography } from '@mui/material';\nimport { Route, Routes, useLocation } from 'react-router-dom';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useNavigateBack } from '../../hooks/useNavigateBack.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useHeaderStore } from '../../stores/header/useHeaderStore.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport {\n backButtonRoutes,\n navigationRoutes,\n navigationRoutesValues,\n} from '../../utils/navigationRoutes.js';\nimport { BackButton } from './BackButton.js';\nimport { CloseDrawerButton } from './CloseDrawerButton.js';\nimport { HeaderAppBar, HeaderControlsContainer } from './Header.style.js';\nimport { NavigationTabs } from './NavigationTabs.js';\nimport { SettingsButton } from './SettingsButton.js';\nimport { TransactionHistoryButton } from './TransactionHistoryButton.js';\nimport { SplitWalletMenuButton } from './WalletHeader.js';\n\nexport const NavigationHeader: React.FC = () => {\n const { subvariant, hiddenUI, variant } = useWidgetConfig();\n const { navigateBack } = useNavigateBack();\n const { account } = useAccount();\n const { element, title } = useHeaderStore((state) => state);\n const { pathname } = useLocation();\n\n const cleanedPathname = pathname.endsWith('/')\n ? pathname.slice(0, -1)\n : pathname;\n const path = cleanedPathname.substring(cleanedPathname.lastIndexOf('/') + 1);\n const hasPath = navigationRoutesValues.includes(path);\n\n const splitSubvariant = subvariant === 'split' && !hasPath;\n\n return (\n <>\n \n {backButtonRoutes.includes(path) ? (\n \n ) : null}\n {splitSubvariant ? (\n \n \n \n ) : (\n \n {title}\n \n )}\n \n \n {account.isConnected &&\n !hiddenUI?.includes(HiddenUI.History) ? (\n \n ) : null}\n \n {variant === 'drawer' &&\n !hiddenUI?.includes(HiddenUI.DrawerCloseButton) ? (\n \n ) : null}\n \n }\n />\n } />\n \n \n {splitSubvariant ? : null}\n \n );\n};\n","import type { FC, PropsWithChildren } from 'react';\nimport { useLayoutEffect, useRef } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { useDefaultElementId } from '../../hooks/useDefaultElementId.js';\nimport { useSetHeaderHeight } from '../../stores/header/useHeaderStore.js';\nimport { ElementId, createElementId } from '../../utils/elements.js';\nimport { stickyHeaderRoutes } from '../../utils/navigationRoutes.js';\nimport { Container } from './Header.style.js';\nimport { NavigationHeader } from './NavigationHeader.js';\nimport { WalletHeader } from './WalletHeader.js';\n\nexport const HeaderContainer: FC> = ({ children }) => {\n const { pathname } = useLocation();\n const elementId = useDefaultElementId();\n const headerRef = useRef(null);\n const { setHeaderHeight } = useSetHeaderHeight();\n\n useLayoutEffect(() => {\n const handleHeaderResize = () => {\n const height = headerRef.current?.getBoundingClientRect().height;\n\n if (height) {\n setHeaderHeight(height);\n }\n };\n\n let resizeObserver: ResizeObserver;\n\n if (headerRef.current) {\n resizeObserver = new ResizeObserver(handleHeaderResize);\n resizeObserver.observe(headerRef.current);\n }\n\n return () => {\n if (resizeObserver) {\n resizeObserver.disconnect();\n }\n };\n }, [headerRef, setHeaderHeight]);\n\n return (\n pathname.includes(route))}\n ref={headerRef}\n >\n {children}\n \n );\n};\n\nexport const Header: FC = () => {\n return (\n \n \n \n \n );\n};\n","import { checkPackageUpdates } from '@lifi/sdk';\nimport { useEffect } from 'react';\nimport { name, version } from '../config/version.js';\nimport { useTools } from './useTools.js';\n\nlet checkedPackageUpdates = false;\n\nexport const useInitializer = () => {\n useTools();\n useEffect(() => {\n if (!checkedPackageUpdates && process.env.NODE_ENV === 'development') {\n checkedPackageUpdates = true;\n checkPackageUpdates(name, version);\n }\n }, []);\n};\n","import { useInitializer } from '../hooks/useInitializer.js';\n\nexport const Initializer: React.FC = () => {\n useInitializer();\n return null;\n};\n","import type { ScopedCssBaselineProps } from '@mui/material';\nimport { Box, Collapse, Grow, ScopedCssBaseline, styled } from '@mui/material';\nimport { defaultMaxHeight } from '../../config/constants.js';\n\nexport const CollapseContainer = styled(Box)(({ theme }) => ({\n zIndex: 0,\n ...(theme.container.display === 'flex'\n ? { display: 'flex', maxHeight: '100%' }\n : { height: 'auto' }),\n}));\n\nexport const RoutesExpandedCollapse = styled(Collapse)(({ theme }) => ({\n ...(theme.container?.display === 'flex' ? { height: '100%' } : {}),\n}));\n\nexport const RouteTopLevelGrow = styled(Grow)(({ theme }) => ({\n ...(theme.container?.display === 'flex' ? { height: '100%' } : {}),\n}));\n\nexport const ScrollableContainer = styled(Box)({\n overflowY: 'auto',\n height: '100%',\n width: '100%',\n flex: 1,\n display: 'flex',\n flexDirection: 'column',\n});\n\ninterface ContainerProps extends ScopedCssBaselineProps {\n minimumHeight: boolean;\n}\n\nexport const Container = styled(ScopedCssBaseline, {\n shouldForwardProp: (prop) => !['minimumHeight'].includes(prop as string),\n})(({ theme, minimumHeight }) => ({\n backgroundColor: theme.palette.background.default,\n overflow: 'auto',\n width: 436,\n marginLeft: theme.spacing(3),\n display: 'flex',\n flexDirection: 'column',\n ...(theme.container?.display !== 'flex'\n ? {\n maxHeight:\n theme.container?.maxHeight ??\n theme.container?.height ??\n defaultMaxHeight,\n ...(minimumHeight ? { '&': { height: 'auto' } } : {}),\n }\n : { height: minimumHeight ? 'auto' : '100%' }),\n ...theme.container,\n}));\n\nexport const Header = styled(Box)(({ theme }) => ({\n backgroundColor: theme.palette.background.default,\n backdropFilter: 'blur(12px)',\n display: 'flex',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: theme.spacing(1.5, 3),\n position: 'sticky',\n top: 0,\n zIndex: 1200,\n}));\n","/* eslint-disable react/no-array-index-key */\nimport type { Route } from '@lifi/sdk';\nimport { Collapse, Grow, Stack, Typography } from '@mui/material';\nimport { useEffect, useRef } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport type { RouteObject } from 'react-router-dom';\nimport { useRoutes as useDOMRoutes, useNavigate } from 'react-router-dom';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useRoutes } from '../../hooks/useRoutes.js';\nimport { useToAddressRequirements } from '../../hooks/useToAddressRequirements.js';\nimport { useWidgetEvents } from '../../hooks/useWidgetEvents.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useFieldValues } from '../../stores/form/useFieldValues.js';\nimport { WidgetEvent } from '../../types/events.js';\nimport { navigationRoutes } from '../../utils/navigationRoutes.js';\nimport { PageContainer } from '../PageContainer.js';\nimport { ProgressToNextUpdate } from '../ProgressToNextUpdate.js';\nimport { RouteCard } from '../RouteCard/RouteCard.js';\nimport { RouteCardSkeleton } from '../RouteCard/RouteCardSkeleton.js';\nimport { RouteNotFoundCard } from '../RouteCard/RouteNotFoundCard.js';\nimport {\n CollapseContainer,\n Container,\n Header,\n RouteTopLevelGrow,\n RoutesExpandedCollapse,\n ScrollableContainer,\n} from './RoutesExpanded.style.js';\n\nconst timeout = { enter: 225, exit: 225, appear: 0 };\n\nconst routes: RouteObject[] = [\n {\n path: '/',\n element: true,\n },\n {\n path: '*',\n element: null,\n },\n];\n\nexport const RoutesExpanded = () => {\n const element = useDOMRoutes(routes);\n const match = Boolean(element?.props?.children);\n\n return (\n \n \n \n
\n \n
\n \n
\n
\n );\n};\n\nexport const RoutesExpandedElement = () => {\n const { t } = useTranslation();\n const navigate = useNavigate();\n const { subvariant } = useWidgetConfig();\n const routesRef = useRef();\n const emitter = useWidgetEvents();\n const routesActiveRef = useRef(false);\n const {\n routes,\n isLoading,\n isFetching,\n isFetched,\n dataUpdatedAt,\n refetchTime,\n fromChain,\n refetch,\n setReviewableRoute,\n } = useRoutes();\n const { account } = useAccount({ chainType: fromChain?.chainType });\n const [toAddress] = useFieldValues('toAddress');\n const { requiredToAddress } = useToAddressRequirements();\n\n const handleRouteClick = (route: Route) => {\n setReviewableRoute(route);\n navigate(navigationRoutes.transactionExecution, {\n state: { routeId: route.id },\n });\n };\n\n const onExit = () => {\n // Clean routes cache on exit\n routesRef.current = undefined;\n };\n\n // We cache routes results in ref for a better exit animation\n if (routesRef.current && !routes) {\n routesActiveRef.current = false;\n } else {\n routesRef.current = routes;\n routesActiveRef.current = Boolean(routes);\n }\n\n const currentRoute = routesRef.current?.[0];\n\n const expanded = Boolean(\n routesActiveRef.current || isLoading || isFetching || isFetched,\n );\n\n const routeNotFound = !currentRoute && !isLoading && !isFetching && expanded;\n const toAddressUnsatisfied = currentRoute && requiredToAddress && !toAddress;\n const allowInteraction = account.isConnected && !toAddressUnsatisfied;\n\n useEffect(() => {\n emitter.emit(WidgetEvent.WidgetExpanded, expanded);\n }, [emitter, expanded]);\n\n return (\n \n \n \n \n
\n \n {subvariant === 'custom'\n ? t('header.youPay')\n : t('header.receive')}\n \n refetch()}\n sx={{ marginRight: -1 }}\n />\n
\n \n \n {routeNotFound ? (\n \n ) : isLoading || (isFetching && !routesRef.current?.length) ? (\n Array.from({ length: 3 }).map((_, index) => (\n \n ))\n ) : (\n routesRef.current?.map((route: Route, index: number) => (\n handleRouteClick(route)\n : undefined\n }\n active={index === 0}\n expanded={routesRef.current?.length === 1}\n />\n ))\n )}\n \n \n
\n
\n
\n \n );\n};\n","'use client';\nimport { AppRoutes } from './AppRoutes.js';\nimport {\n AppContainer,\n AppExpandedContainer,\n FlexContainer,\n} from './components/AppContainer.js';\nimport { Header } from './components/Header/Header.js';\nimport { Initializer } from './components/Initializer.js';\nimport { RoutesExpanded } from './components/Routes/RoutesExpanded.js';\nimport { useWideVariant } from './hooks/useWideVariant.js';\nimport { useWidgetConfig } from './providers/WidgetProvider/WidgetProvider.js';\nimport { ElementId, createElementId } from './utils/elements.js';\n\nexport const AppDefault = () => {\n const { elementId } = useWidgetConfig();\n const wideVariant = useWideVariant();\n\n return (\n \n \n
\n \n \n \n \n \n {wideVariant ? : null}\n \n );\n};\n","import { Drawer } from '@mui/material';\nimport type { PropsWithChildren } from 'react';\nimport {\n forwardRef,\n useCallback,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport type { WidgetDrawerContext } from './AppDrawerContext.js';\nimport { DrawerContext } from './AppDrawerContext.js';\nimport type { WidgetDrawerProps } from './types/widget.js';\n\nexport interface WidgetDrawer {\n isOpen(): void;\n toggleDrawer(): void;\n openDrawer(): void;\n closeDrawer(): void;\n}\n\nexport const AppDrawer = forwardRef<\n WidgetDrawer,\n PropsWithChildren\n>(({ elementRef, open, onClose, config, children }, ref) => {\n const openRef = useRef(Boolean(open));\n const [drawerOpen, setDrawerOpen] = useState(Boolean(open));\n\n const toggleDrawer = useCallback(() => {\n setDrawerOpen((open) => {\n openRef.current = !open;\n return openRef.current;\n });\n if (!openRef.current) {\n onClose?.();\n }\n }, [onClose]);\n\n const openDrawer = useCallback(() => {\n setDrawerOpen(true);\n openRef.current = true;\n }, []);\n\n const closeDrawer = useCallback(() => {\n setDrawerOpen(false);\n openRef.current = false;\n onClose?.();\n }, [onClose]);\n\n useImperativeHandle(\n ref,\n () => ({\n isOpen: () => openRef.current,\n toggleDrawer,\n openDrawer,\n closeDrawer,\n }),\n [closeDrawer, openDrawer, toggleDrawer],\n );\n\n const drawerContext: WidgetDrawerContext = useMemo(\n () => ({\n closeDrawer,\n }),\n [closeDrawer],\n );\n\n return (\n \n ({\n width: theme?.container?.width ?? '100%',\n minWidth: theme?.container?.minWidth ?? theme.breakpoints.values.xs,\n maxWidth: theme?.container?.maxWidth ?? theme.breakpoints.values.sm,\n }),\n }}\n keepMounted\n >\n {children}\n \n \n );\n});\n","import { useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { useWidgetEvents } from '../hooks/useWidgetEvents.js';\nimport { WidgetEvent } from '../types/events.js';\n\nexport function PageEntered() {\n const location = useLocation();\n const emitter = useWidgetEvents();\n\n useEffect(() => {\n emitter.emit(WidgetEvent.PageEntered, location.pathname);\n }, [emitter, location.pathname]);\n return null;\n}\n","import { hashQueryKeyByOptions, matchQuery } from './utils'\nimport { Query } from './query'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport type { QueryFilters } from './utils'\nimport type { Action, QueryState } from './query'\nimport type {\n DefaultError,\n NotifyEvent,\n QueryKey,\n QueryOptions,\n WithRequired,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { QueryObserver } from './queryObserver'\n\n// TYPES\n\ninterface QueryCacheConfig {\n onError?: (\n error: DefaultError,\n query: Query,\n ) => void\n onSuccess?: (data: unknown, query: Query) => void\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n query: Query,\n ) => void\n}\n\ninterface NotifyEventQueryAdded extends NotifyEvent {\n type: 'added'\n query: Query\n}\n\ninterface NotifyEventQueryRemoved extends NotifyEvent {\n type: 'removed'\n query: Query\n}\n\ninterface NotifyEventQueryUpdated extends NotifyEvent {\n type: 'updated'\n query: Query\n action: Action\n}\n\ninterface NotifyEventQueryObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n query: Query\n observer: QueryObserver\n}\n\ninterface NotifyEventQueryObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n query: Query\n observer: QueryObserver\n}\n\ninterface NotifyEventQueryObserverResultsUpdated extends NotifyEvent {\n type: 'observerResultsUpdated'\n query: Query\n}\n\ninterface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n query: Query\n observer: QueryObserver\n}\n\nexport type QueryCacheNotifyEvent =\n | NotifyEventQueryAdded\n | NotifyEventQueryRemoved\n | NotifyEventQueryUpdated\n | NotifyEventQueryObserverAdded\n | NotifyEventQueryObserverRemoved\n | NotifyEventQueryObserverResultsUpdated\n | NotifyEventQueryObserverOptionsUpdated\n\ntype QueryCacheListener = (event: QueryCacheNotifyEvent) => void\n\nexport interface QueryStore {\n has: (queryHash: string) => boolean\n set: (queryHash: string, query: Query) => void\n get: (queryHash: string) => Query | undefined\n delete: (queryHash: string) => void\n values: () => IterableIterator\n}\n\n// CLASS\n\nexport class QueryCache extends Subscribable {\n #queries: QueryStore\n\n constructor(public config: QueryCacheConfig = {}) {\n super()\n this.#queries = new Map()\n }\n\n build<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n client: QueryClient,\n options: WithRequired<\n QueryOptions,\n 'queryKey'\n >,\n state?: QueryState,\n ): Query {\n const queryKey = options.queryKey\n const queryHash =\n options.queryHash ?? hashQueryKeyByOptions(queryKey, options)\n let query = this.get(queryHash)\n\n if (!query) {\n query = new Query({\n cache: this,\n queryKey,\n queryHash,\n options: client.defaultQueryOptions(options),\n state,\n defaultOptions: client.getQueryDefaults(queryKey),\n })\n this.add(query)\n }\n\n return query\n }\n\n add(query: Query): void {\n if (!this.#queries.has(query.queryHash)) {\n this.#queries.set(query.queryHash, query)\n\n this.notify({\n type: 'added',\n query,\n })\n }\n }\n\n remove(query: Query): void {\n const queryInMap = this.#queries.get(query.queryHash)\n\n if (queryInMap) {\n query.destroy()\n\n if (queryInMap === query) {\n this.#queries.delete(query.queryHash)\n }\n\n this.notify({ type: 'removed', query })\n }\n }\n\n clear(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n this.remove(query)\n })\n })\n }\n\n get<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n queryHash: string,\n ): Query | undefined {\n return this.#queries.get(queryHash) as\n | Query\n | undefined\n }\n\n getAll(): Array {\n return [...this.#queries.values()]\n }\n\n find(\n filters: WithRequired,\n ): Query | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((query) =>\n matchQuery(defaultedFilters, query),\n ) as Query | undefined\n }\n\n findAll(filters: QueryFilters = {}): Array {\n const queries = this.getAll()\n return Object.keys(filters).length > 0\n ? queries.filter((query) => matchQuery(filters, query))\n : queries\n }\n\n notify(event: QueryCacheNotifyEvent) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n onFocus(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onFocus()\n })\n })\n }\n\n onOnline(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onOnline()\n })\n })\n }\n}\n","import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type { DefaultError, MutationOptions, NotifyEvent } from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\ninterface MutationCacheConfig {\n onError?: (\n error: DefaultError,\n variables: unknown,\n context: unknown,\n mutation: Mutation,\n ) => Promise | unknown\n onSuccess?: (\n data: unknown,\n variables: unknown,\n context: unknown,\n mutation: Mutation,\n ) => Promise | unknown\n onMutate?: (\n variables: unknown,\n mutation: Mutation,\n ) => Promise | unknown\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n context: unknown,\n mutation: Mutation,\n ) => Promise | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation\n observer: MutationObserver\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation\n observer: MutationObserver\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation\n observer: MutationObserver\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation\n action: Action\n}\n\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\nexport class MutationCache extends Subscribable {\n #mutations: Map>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Map()\n this.#mutationId = Date.now()\n }\n\n build(\n client: QueryClient,\n options: MutationOptions,\n state?: MutationState,\n ): Mutation {\n const mutation = new Mutation({\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state,\n })\n\n this.add(mutation)\n\n return mutation\n }\n\n add(mutation: Mutation): void {\n const scope = scopeFor(mutation)\n const mutations = this.#mutations.get(scope) ?? []\n mutations.push(mutation)\n this.#mutations.set(scope, mutations)\n this.notify({ type: 'added', mutation })\n }\n\n remove(mutation: Mutation): void {\n const scope = scopeFor(mutation)\n if (this.#mutations.has(scope)) {\n const mutations = this.#mutations\n .get(scope)\n ?.filter((x) => x !== mutation)\n if (mutations) {\n if (mutations.length === 0) {\n this.#mutations.delete(scope)\n } else {\n this.#mutations.set(scope, mutations)\n }\n }\n }\n\n this.notify({ type: 'removed', mutation })\n }\n\n canRun(mutation: Mutation): boolean {\n const firstPendingMutation = this.#mutations\n .get(scopeFor(mutation))\n ?.find((m) => m.state.status === 'pending')\n\n // we can run if there is no current pending mutation (start use-case)\n // or if WE are the first pending mutation (continue use-case)\n return !firstPendingMutation || firstPendingMutation === mutation\n }\n\n runNext(mutation: Mutation): Promise {\n const foundMutation = this.#mutations\n .get(scopeFor(mutation))\n ?.find((m) => m !== mutation && m.state.isPaused)\n\n return foundMutation?.continue() ?? Promise.resolve()\n }\n\n clear(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((mutation) => {\n this.remove(mutation)\n })\n })\n }\n\n getAll(): Array {\n return [...this.#mutations.values()].flat()\n }\n\n find<\n TData = unknown,\n TError = DefaultError,\n TVariables = any,\n TContext = unknown,\n >(\n filters: MutationFilters,\n ): Mutation | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((mutation) =>\n matchMutation(defaultedFilters, mutation),\n ) as Mutation | undefined\n }\n\n findAll(filters: MutationFilters = {}): Array {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation))\n }\n\n notify(event: MutationCacheNotifyEvent) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n resumePausedMutations(): Promise {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused)\n\n return notifyManager.batch(() =>\n Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop)),\n ),\n )\n }\n}\n\nfunction scopeFor(mutation: Mutation) {\n return mutation.options.scope?.id ?? String(mutation.mutationId)\n}\n","import { addToEnd, addToStart, ensureQueryFn } from './utils'\nimport type { QueryBehavior } from './query'\nimport type {\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n} from './types'\n\nexport function infiniteQueryBehavior(\n pages?: number,\n): QueryBehavior> {\n return {\n onFetch: (context, query) => {\n const options = context.options as InfiniteQueryPageParamsOptions\n const direction = context.fetchOptions?.meta?.fetchMore?.direction\n const oldPages = context.state.data?.pages || []\n const oldPageParams = context.state.data?.pageParams || []\n let result: InfiniteData = { pages: [], pageParams: [] }\n let currentPage = 0\n\n const fetchFn = async () => {\n let cancelled = false\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n if (context.signal.aborted) {\n cancelled = true\n } else {\n context.signal.addEventListener('abort', () => {\n cancelled = true\n })\n }\n return context.signal\n },\n })\n }\n\n const queryFn = ensureQueryFn(context.options, context.fetchOptions)\n\n // Create function to fetch a page\n const fetchPage = async (\n data: InfiniteData,\n param: unknown,\n previous?: boolean,\n ): Promise> => {\n if (cancelled) {\n return Promise.reject()\n }\n\n if (param == null && data.pages.length) {\n return Promise.resolve(data)\n }\n\n const queryFnContext: OmitKeyof<\n QueryFunctionContext,\n 'signal'\n > = {\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? 'backward' : 'forward',\n meta: context.options.meta,\n }\n\n addSignalProperty(queryFnContext)\n\n const page = await queryFn(\n queryFnContext as QueryFunctionContext,\n )\n\n const { maxPages } = context.options\n const addTo = previous ? addToStart : addToEnd\n\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages),\n }\n }\n\n // fetch next / previous page?\n if (direction && oldPages.length) {\n const previous = direction === 'backward'\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams,\n }\n const param = pageParamFn(options, oldData)\n\n result = await fetchPage(oldData, param, previous)\n } else {\n const remainingPages = pages ?? oldPages.length\n\n // Fetch all pages\n do {\n const param =\n currentPage === 0\n ? (oldPageParams[0] ?? options.initialPageParam)\n : getNextPageParam(options, result)\n if (currentPage > 0 && param == null) {\n break\n }\n result = await fetchPage(result, param)\n currentPage++\n } while (currentPage < remainingPages)\n }\n\n return result\n }\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn as any,\n {\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal,\n },\n query,\n )\n }\n } else {\n context.fetchFn = fetchFn\n }\n },\n }\n}\n\nfunction getNextPageParam(\n options: InfiniteQueryPageParamsOptions,\n { pages, pageParams }: InfiniteData,\n): unknown | undefined {\n const lastIndex = pages.length - 1\n return pages.length > 0\n ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams,\n )\n : undefined\n}\n\nfunction getPreviousPageParam(\n options: InfiniteQueryPageParamsOptions,\n { pages, pageParams }: InfiniteData,\n): unknown | undefined {\n return pages.length > 0\n ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)\n : undefined\n}\n\n/**\n * Checks if there is a next page.\n */\nexport function hasNextPage(\n options: InfiniteQueryPageParamsOptions,\n data?: InfiniteData,\n): boolean {\n if (!data) return false\n return getNextPageParam(options, data) != null\n}\n\n/**\n * Checks if there is a previous page.\n */\nexport function hasPreviousPage(\n options: InfiniteQueryPageParamsOptions,\n data?: InfiniteData,\n): boolean {\n if (!data || !options.getPreviousPageParam) return false\n return getPreviousPageParam(options, data) != null\n}\n","import { QueryClient } from '@tanstack/react-query';\n\nexport const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n enabled: true,\n refetchInterval: false,\n refetchIntervalInBackground: false,\n refetchOnWindowFocus: true,\n refetchOnReconnect: true,\n refetchOnMount: true,\n retryOnMount: true,\n // suspense: true,\n },\n mutations: {\n onError: (error) => {\n //\n },\n },\n },\n});\n","import {\n functionalUpdate,\n hashKey,\n hashQueryKeyByOptions,\n noop,\n partialMatchKey,\n resolveStaleTime,\n skipToken,\n} from './utils'\nimport { QueryCache } from './queryCache'\nimport { MutationCache } from './mutationCache'\nimport { focusManager } from './focusManager'\nimport { onlineManager } from './onlineManager'\nimport { notifyManager } from './notifyManager'\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport type {\n CancelOptions,\n DataTag,\n DefaultError,\n DefaultOptions,\n DefaultedQueryObserverOptions,\n EnsureInfiniteQueryDataOptions,\n EnsureQueryDataOptions,\n FetchInfiniteQueryOptions,\n FetchQueryOptions,\n InfiniteData,\n InvalidateOptions,\n InvalidateQueryFilters,\n MutationKey,\n MutationObserverOptions,\n MutationOptions,\n NoInfer,\n OmitKeyof,\n QueryClientConfig,\n QueryKey,\n QueryObserverOptions,\n QueryOptions,\n RefetchOptions,\n RefetchQueryFilters,\n ResetOptions,\n SetDataOptions,\n} from './types'\nimport type { QueryState } from './query'\nimport type { MutationFilters, QueryFilters, Updater } from './utils'\n\n// TYPES\n\ninterface QueryDefaults {\n queryKey: QueryKey\n defaultOptions: OmitKeyof, 'queryKey'>\n}\n\ninterface MutationDefaults {\n mutationKey: MutationKey\n defaultOptions: MutationOptions\n}\n\n// CLASS\n\nexport class QueryClient {\n #queryCache: QueryCache\n #mutationCache: MutationCache\n #defaultOptions: DefaultOptions\n #queryDefaults: Map\n #mutationDefaults: Map\n #mountCount: number\n #unsubscribeFocus?: () => void\n #unsubscribeOnline?: () => void\n\n constructor(config: QueryClientConfig = {}) {\n this.#queryCache = config.queryCache || new QueryCache()\n this.#mutationCache = config.mutationCache || new MutationCache()\n this.#defaultOptions = config.defaultOptions || {}\n this.#queryDefaults = new Map()\n this.#mutationDefaults = new Map()\n this.#mountCount = 0\n }\n\n mount(): void {\n this.#mountCount++\n if (this.#mountCount !== 1) return\n\n this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {\n if (focused) {\n await this.resumePausedMutations()\n this.#queryCache.onFocus()\n }\n })\n this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {\n if (online) {\n await this.resumePausedMutations()\n this.#queryCache.onOnline()\n }\n })\n }\n\n unmount(): void {\n this.#mountCount--\n if (this.#mountCount !== 0) return\n\n this.#unsubscribeFocus?.()\n this.#unsubscribeFocus = undefined\n\n this.#unsubscribeOnline?.()\n this.#unsubscribeOnline = undefined\n }\n\n isFetching(filters?: QueryFilters): number {\n return this.#queryCache.findAll({ ...filters, fetchStatus: 'fetching' })\n .length\n }\n\n isMutating(filters?: MutationFilters): number {\n return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length\n }\n\n getQueryData<\n TQueryFnData = unknown,\n TTaggedQueryKey extends QueryKey = QueryKey,\n TInferredQueryFnData = TTaggedQueryKey extends DataTag<\n unknown,\n infer TaggedValue\n >\n ? TaggedValue\n : TQueryFnData,\n >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined\n getQueryData(queryKey: QueryKey) {\n const options = this.defaultQueryOptions({ queryKey })\n return this.#queryCache.get(options.queryHash)?.state.data\n }\n\n ensureQueryData<\n TQueryFnData,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: EnsureQueryDataOptions,\n ): Promise {\n const cachedData = this.getQueryData(options.queryKey)\n\n if (cachedData === undefined) return this.fetchQuery(options)\n else {\n const defaultedOptions = this.defaultQueryOptions(options)\n const query = this.#queryCache.build(this, defaultedOptions)\n\n if (\n options.revalidateIfStale &&\n query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))\n ) {\n void this.prefetchQuery(defaultedOptions)\n }\n\n return Promise.resolve(cachedData)\n }\n }\n\n getQueriesData(\n filters: QueryFilters,\n ): Array<[QueryKey, TQueryFnData | undefined]> {\n return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {\n const data = state.data as TQueryFnData | undefined\n return [queryKey, data]\n })\n }\n\n setQueryData<\n TQueryFnData = unknown,\n TTaggedQueryKey extends QueryKey = QueryKey,\n TInferredQueryFnData = TTaggedQueryKey extends DataTag<\n unknown,\n infer TaggedValue\n >\n ? TaggedValue\n : TQueryFnData,\n >(\n queryKey: TTaggedQueryKey,\n updater: Updater<\n NoInfer | undefined,\n NoInfer | undefined\n >,\n options?: SetDataOptions,\n ): TInferredQueryFnData | undefined {\n const defaultedOptions = this.defaultQueryOptions<\n any,\n any,\n unknown,\n any,\n QueryKey\n >({ queryKey })\n\n const query = this.#queryCache.get(\n defaultedOptions.queryHash,\n )\n const prevData = query?.state.data\n const data = functionalUpdate(updater, prevData)\n\n if (data === undefined) {\n return undefined\n }\n\n return this.#queryCache\n .build(this, defaultedOptions)\n .setData(data, { ...options, manual: true })\n }\n\n setQueriesData(\n filters: QueryFilters,\n updater: Updater,\n options?: SetDataOptions,\n ): Array<[QueryKey, TQueryFnData | undefined]> {\n return notifyManager.batch(() =>\n this.#queryCache\n .findAll(filters)\n .map(({ queryKey }) => [\n queryKey,\n this.setQueryData(queryKey, updater, options),\n ]),\n )\n }\n\n getQueryState<\n TQueryFnData = unknown,\n TError = DefaultError,\n TTaggedQueryKey extends QueryKey = QueryKey,\n TInferredQueryFnData = TTaggedQueryKey extends DataTag<\n unknown,\n infer TaggedValue\n >\n ? TaggedValue\n : TQueryFnData,\n >(\n queryKey: TTaggedQueryKey,\n ): QueryState | undefined {\n const options = this.defaultQueryOptions({ queryKey })\n return this.#queryCache.get(options.queryHash)\n ?.state\n }\n\n removeQueries(filters?: QueryFilters): void {\n const queryCache = this.#queryCache\n notifyManager.batch(() => {\n queryCache.findAll(filters).forEach((query) => {\n queryCache.remove(query)\n })\n })\n }\n\n resetQueries(filters?: QueryFilters, options?: ResetOptions): Promise {\n const queryCache = this.#queryCache\n\n const refetchFilters: RefetchQueryFilters = {\n type: 'active',\n ...filters,\n }\n\n return notifyManager.batch(() => {\n queryCache.findAll(filters).forEach((query) => {\n query.reset()\n })\n return this.refetchQueries(refetchFilters, options)\n })\n }\n\n cancelQueries(\n filters: QueryFilters = {},\n cancelOptions: CancelOptions = {},\n ): Promise {\n const defaultedCancelOptions = { revert: true, ...cancelOptions }\n\n const promises = notifyManager.batch(() =>\n this.#queryCache\n .findAll(filters)\n .map((query) => query.cancel(defaultedCancelOptions)),\n )\n\n return Promise.all(promises).then(noop).catch(noop)\n }\n\n invalidateQueries(\n filters: InvalidateQueryFilters = {},\n options: InvalidateOptions = {},\n ): Promise {\n return notifyManager.batch(() => {\n this.#queryCache.findAll(filters).forEach((query) => {\n query.invalidate()\n })\n\n if (filters.refetchType === 'none') {\n return Promise.resolve()\n }\n const refetchFilters: RefetchQueryFilters = {\n ...filters,\n type: filters.refetchType ?? filters.type ?? 'active',\n }\n return this.refetchQueries(refetchFilters, options)\n })\n }\n\n refetchQueries(\n filters: RefetchQueryFilters = {},\n options?: RefetchOptions,\n ): Promise {\n const fetchOptions = {\n ...options,\n cancelRefetch: options?.cancelRefetch ?? true,\n }\n const promises = notifyManager.batch(() =>\n this.#queryCache\n .findAll(filters)\n .filter((query) => !query.isDisabled())\n .map((query) => {\n let promise = query.fetch(undefined, fetchOptions)\n if (!fetchOptions.throwOnError) {\n promise = promise.catch(noop)\n }\n return query.state.fetchStatus === 'paused'\n ? Promise.resolve()\n : promise\n }),\n )\n\n return Promise.all(promises).then(noop)\n }\n\n fetchQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = never,\n >(\n options: FetchQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): Promise {\n const defaultedOptions = this.defaultQueryOptions(options)\n\n // https://github.com/tannerlinsley/react-query/issues/652\n if (defaultedOptions.retry === undefined) {\n defaultedOptions.retry = false\n }\n\n const query = this.#queryCache.build(this, defaultedOptions)\n\n return query.isStaleByTime(\n resolveStaleTime(defaultedOptions.staleTime, query),\n )\n ? query.fetch(defaultedOptions)\n : Promise.resolve(query.state.data as TData)\n }\n\n prefetchQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: FetchQueryOptions,\n ): Promise {\n return this.fetchQuery(options).then(noop).catch(noop)\n }\n\n fetchInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n >(\n options: FetchInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): Promise> {\n options.behavior = infiniteQueryBehavior<\n TQueryFnData,\n TError,\n TData,\n TPageParam\n >(options.pages)\n return this.fetchQuery(options as any)\n }\n\n prefetchInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n >(\n options: FetchInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): Promise {\n return this.fetchInfiniteQuery(options).then(noop).catch(noop)\n }\n\n ensureInfiniteQueryData<\n TQueryFnData,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n >(\n options: EnsureInfiniteQueryDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n ): Promise> {\n options.behavior = infiniteQueryBehavior<\n TQueryFnData,\n TError,\n TData,\n TPageParam\n >(options.pages)\n\n return this.ensureQueryData(options as any)\n }\n\n resumePausedMutations(): Promise {\n if (onlineManager.isOnline()) {\n return this.#mutationCache.resumePausedMutations()\n }\n return Promise.resolve()\n }\n\n getQueryCache(): QueryCache {\n return this.#queryCache\n }\n\n getMutationCache(): MutationCache {\n return this.#mutationCache\n }\n\n getDefaultOptions(): DefaultOptions {\n return this.#defaultOptions\n }\n\n setDefaultOptions(options: DefaultOptions): void {\n this.#defaultOptions = options\n }\n\n setQueryDefaults<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n >(\n queryKey: QueryKey,\n options: Partial<\n OmitKeyof<\n QueryObserverOptions,\n 'queryKey'\n >\n >,\n ): void {\n this.#queryDefaults.set(hashKey(queryKey), {\n queryKey,\n defaultOptions: options,\n })\n }\n\n getQueryDefaults(\n queryKey: QueryKey,\n ): OmitKeyof, 'queryKey'> {\n const defaults = [...this.#queryDefaults.values()]\n\n let result: OmitKeyof<\n QueryObserverOptions,\n 'queryKey'\n > = {}\n\n defaults.forEach((queryDefault) => {\n if (partialMatchKey(queryKey, queryDefault.queryKey)) {\n result = { ...result, ...queryDefault.defaultOptions }\n }\n })\n return result\n }\n\n setMutationDefaults<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TContext = unknown,\n >(\n mutationKey: MutationKey,\n options: OmitKeyof<\n MutationObserverOptions,\n 'mutationKey'\n >,\n ): void {\n this.#mutationDefaults.set(hashKey(mutationKey), {\n mutationKey,\n defaultOptions: options,\n })\n }\n\n getMutationDefaults(\n mutationKey: MutationKey,\n ): MutationObserverOptions {\n const defaults = [...this.#mutationDefaults.values()]\n\n let result: MutationObserverOptions = {}\n\n defaults.forEach((queryDefault) => {\n if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {\n result = { ...result, ...queryDefault.defaultOptions }\n }\n })\n\n return result\n }\n\n defaultQueryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = never,\n >(\n options:\n | QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey,\n TPageParam\n >\n | DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n ): DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n > {\n if (options._defaulted) {\n return options as DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n }\n\n const defaultedOptions = {\n ...this.#defaultOptions.queries,\n ...this.getQueryDefaults(options.queryKey),\n ...options,\n _defaulted: true,\n }\n\n if (!defaultedOptions.queryHash) {\n defaultedOptions.queryHash = hashQueryKeyByOptions(\n defaultedOptions.queryKey,\n defaultedOptions,\n )\n }\n\n // dependent default values\n if (defaultedOptions.refetchOnReconnect === undefined) {\n defaultedOptions.refetchOnReconnect =\n defaultedOptions.networkMode !== 'always'\n }\n if (defaultedOptions.throwOnError === undefined) {\n defaultedOptions.throwOnError = !!defaultedOptions.suspense\n }\n\n if (!defaultedOptions.networkMode && defaultedOptions.persister) {\n defaultedOptions.networkMode = 'offlineFirst'\n }\n\n if (\n defaultedOptions.enabled !== true &&\n defaultedOptions.queryFn === skipToken\n ) {\n defaultedOptions.enabled = false\n }\n\n return defaultedOptions as DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >\n }\n\n defaultMutationOptions>(\n options?: T,\n ): T {\n if (options?._defaulted) {\n return options\n }\n return {\n ...this.#defaultOptions.mutations,\n ...(options?.mutationKey &&\n this.getMutationDefaults(options.mutationKey)),\n ...options,\n _defaulted: true,\n } as T\n }\n\n clear(): void {\n this.#queryCache.clear()\n this.#mutationCache.clear()\n }\n}\n","const consoleLogger = {\n type: 'logger',\n log(args) {\n this.output('log', args);\n },\n warn(args) {\n this.output('warn', args);\n },\n error(args) {\n this.output('error', args);\n },\n output(type, args) {\n if (console && console[type]) console[type].apply(console, args);\n }\n};\nclass Logger {\n constructor(concreteLogger) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n this.init(concreteLogger, options);\n }\n init(concreteLogger) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n this.prefix = options.prefix || 'i18next:';\n this.logger = concreteLogger || consoleLogger;\n this.options = options;\n this.debug = options.debug;\n }\n log() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return this.forward(args, 'log', '', true);\n }\n warn() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n return this.forward(args, 'warn', '', true);\n }\n error() {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n return this.forward(args, 'error', '');\n }\n deprecate() {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);\n }\n forward(args, lvl, prefix, debugOnly) {\n if (debugOnly && !this.debug) return null;\n if (typeof args[0] === 'string') args[0] = `${prefix}${this.prefix} ${args[0]}`;\n return this.logger[lvl](args);\n }\n create(moduleName) {\n return new Logger(this.logger, {\n ...{\n prefix: `${this.prefix}:${moduleName}:`\n },\n ...this.options\n });\n }\n clone(options) {\n options = options || this.options;\n options.prefix = options.prefix || this.prefix;\n return new Logger(this.logger, options);\n }\n}\nvar baseLogger = new Logger();\n\nclass EventEmitter {\n constructor() {\n this.observers = {};\n }\n on(events, listener) {\n events.split(' ').forEach(event => {\n if (!this.observers[event]) this.observers[event] = new Map();\n const numListeners = this.observers[event].get(listener) || 0;\n this.observers[event].set(listener, numListeners + 1);\n });\n return this;\n }\n off(event, listener) {\n if (!this.observers[event]) return;\n if (!listener) {\n delete this.observers[event];\n return;\n }\n this.observers[event].delete(listener);\n }\n emit(event) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n if (this.observers[event]) {\n const cloned = Array.from(this.observers[event].entries());\n cloned.forEach(_ref => {\n let [observer, numTimesAdded] = _ref;\n for (let i = 0; i < numTimesAdded; i++) {\n observer(...args);\n }\n });\n }\n if (this.observers['*']) {\n const cloned = Array.from(this.observers['*'].entries());\n cloned.forEach(_ref2 => {\n let [observer, numTimesAdded] = _ref2;\n for (let i = 0; i < numTimesAdded; i++) {\n observer.apply(observer, [event, ...args]);\n }\n });\n }\n }\n}\n\nfunction defer() {\n let res;\n let rej;\n const promise = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n promise.resolve = res;\n promise.reject = rej;\n return promise;\n}\nfunction makeString(object) {\n if (object == null) return '';\n return '' + object;\n}\nfunction copy(a, s, t) {\n a.forEach(m => {\n if (s[m]) t[m] = s[m];\n });\n}\nconst lastOfPathSeparatorRegExp = /###/g;\nfunction getLastOfPath(object, path, Empty) {\n function cleanKey(key) {\n return key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;\n }\n function canNotTraverseDeeper() {\n return !object || typeof object === 'string';\n }\n const stack = typeof path !== 'string' ? path : path.split('.');\n let stackIndex = 0;\n while (stackIndex < stack.length - 1) {\n if (canNotTraverseDeeper()) return {};\n const key = cleanKey(stack[stackIndex]);\n if (!object[key] && Empty) object[key] = new Empty();\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n object = object[key];\n } else {\n object = {};\n }\n ++stackIndex;\n }\n if (canNotTraverseDeeper()) return {};\n return {\n obj: object,\n k: cleanKey(stack[stackIndex])\n };\n}\nfunction setPath(object, path, newValue) {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n if (obj !== undefined || path.length === 1) {\n obj[k] = newValue;\n return;\n }\n let e = path[path.length - 1];\n let p = path.slice(0, path.length - 1);\n let last = getLastOfPath(object, p, Object);\n while (last.obj === undefined && p.length) {\n e = `${p[p.length - 1]}.${e}`;\n p = p.slice(0, p.length - 1);\n last = getLastOfPath(object, p, Object);\n if (last && last.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {\n last.obj = undefined;\n }\n }\n last.obj[`${last.k}.${e}`] = newValue;\n}\nfunction pushPath(object, path, newValue, concat) {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n obj[k] = obj[k] || [];\n if (concat) obj[k] = obj[k].concat(newValue);\n if (!concat) obj[k].push(newValue);\n}\nfunction getPath(object, path) {\n const {\n obj,\n k\n } = getLastOfPath(object, path);\n if (!obj) return undefined;\n return obj[k];\n}\nfunction getPathWithDefaults(data, defaultData, key) {\n const value = getPath(data, key);\n if (value !== undefined) {\n return value;\n }\n return getPath(defaultData, key);\n}\nfunction deepExtend(target, source, overwrite) {\n for (const prop in source) {\n if (prop !== '__proto__' && prop !== 'constructor') {\n if (prop in target) {\n if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {\n if (overwrite) target[prop] = source[prop];\n } else {\n deepExtend(target[prop], source[prop], overwrite);\n }\n } else {\n target[prop] = source[prop];\n }\n }\n }\n return target;\n}\nfunction regexEscape(str) {\n return str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\n}\nvar _entityMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/'\n};\nfunction escape(data) {\n if (typeof data === 'string') {\n return data.replace(/[&<>\"'\\/]/g, s => _entityMap[s]);\n }\n return data;\n}\nclass RegExpCache {\n constructor(capacity) {\n this.capacity = capacity;\n this.regExpMap = new Map();\n this.regExpQueue = [];\n }\n getRegExp(pattern) {\n const regExpFromCache = this.regExpMap.get(pattern);\n if (regExpFromCache !== undefined) {\n return regExpFromCache;\n }\n const regExpNew = new RegExp(pattern);\n if (this.regExpQueue.length === this.capacity) {\n this.regExpMap.delete(this.regExpQueue.shift());\n }\n this.regExpMap.set(pattern, regExpNew);\n this.regExpQueue.push(pattern);\n return regExpNew;\n }\n}\nconst chars = [' ', ',', '?', '!', ';'];\nconst looksLikeObjectPathRegExpCache = new RegExpCache(20);\nfunction looksLikeObjectPath(key, nsSeparator, keySeparator) {\n nsSeparator = nsSeparator || '';\n keySeparator = keySeparator || '';\n const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);\n if (possibleChars.length === 0) return true;\n const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\\\?' : c).join('|')})`);\n let matched = !r.test(key);\n if (!matched) {\n const ki = key.indexOf(keySeparator);\n if (ki > 0 && !r.test(key.substring(0, ki))) {\n matched = true;\n }\n }\n return matched;\n}\nfunction deepFind(obj, path) {\n let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';\n if (!obj) return undefined;\n if (obj[path]) return obj[path];\n const tokens = path.split(keySeparator);\n let current = obj;\n for (let i = 0; i < tokens.length;) {\n if (!current || typeof current !== 'object') {\n return undefined;\n }\n let next;\n let nextPath = '';\n for (let j = i; j < tokens.length; ++j) {\n if (j !== i) {\n nextPath += keySeparator;\n }\n nextPath += tokens[j];\n next = current[nextPath];\n if (next !== undefined) {\n if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {\n continue;\n }\n i += j - i + 1;\n break;\n }\n }\n current = next;\n }\n return current;\n}\nfunction getCleanedCode(code) {\n if (code && code.indexOf('_') > 0) return code.replace('_', '-');\n return code;\n}\n\nclass ResourceStore extends EventEmitter {\n constructor(data) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n ns: ['translation'],\n defaultNS: 'translation'\n };\n super();\n this.data = data || {};\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n if (this.options.ignoreJSONStructure === undefined) {\n this.options.ignoreJSONStructure = true;\n }\n }\n addNamespaces(ns) {\n if (this.options.ns.indexOf(ns) < 0) {\n this.options.ns.push(ns);\n }\n }\n removeNamespaces(ns) {\n const index = this.options.ns.indexOf(ns);\n if (index > -1) {\n this.options.ns.splice(index, 1);\n }\n }\n getResource(lng, ns, key) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;\n let path;\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n } else {\n path = [lng, ns];\n if (key) {\n if (Array.isArray(key)) {\n path.push(...key);\n } else if (typeof key === 'string' && keySeparator) {\n path.push(...key.split(keySeparator));\n } else {\n path.push(key);\n }\n }\n }\n const result = getPath(this.data, path);\n if (!result && !ns && !key && lng.indexOf('.') > -1) {\n lng = path[0];\n ns = path[1];\n key = path.slice(2).join('.');\n }\n if (result || !ignoreJSONStructure || typeof key !== 'string') return result;\n return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);\n }\n addResource(lng, ns, key, value) {\n let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {\n silent: false\n };\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n let path = [lng, ns];\n if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n value = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n setPath(this.data, path, value);\n if (!options.silent) this.emit('added', lng, ns, key, value);\n }\n addResources(lng, ns, resources) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {\n silent: false\n };\n for (const m in resources) {\n if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {\n silent: true\n });\n }\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n addResourceBundle(lng, ns, resources, deep, overwrite) {\n let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {\n silent: false,\n skipCopy: false\n };\n let path = [lng, ns];\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n deep = resources;\n resources = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n let pack = getPath(this.data, path) || {};\n if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));\n if (deep) {\n deepExtend(pack, resources, overwrite);\n } else {\n pack = {\n ...pack,\n ...resources\n };\n }\n setPath(this.data, path, pack);\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n removeResourceBundle(lng, ns) {\n if (this.hasResourceBundle(lng, ns)) {\n delete this.data[lng][ns];\n }\n this.removeNamespaces(ns);\n this.emit('removed', lng, ns);\n }\n hasResourceBundle(lng, ns) {\n return this.getResource(lng, ns) !== undefined;\n }\n getResourceBundle(lng, ns) {\n if (!ns) ns = this.options.defaultNS;\n if (this.options.compatibilityAPI === 'v1') return {\n ...{},\n ...this.getResource(lng, ns)\n };\n return this.getResource(lng, ns);\n }\n getDataByLanguage(lng) {\n return this.data[lng];\n }\n hasLanguageSomeTranslations(lng) {\n const data = this.getDataByLanguage(lng);\n const n = data && Object.keys(data) || [];\n return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);\n }\n toJSON() {\n return this.data;\n }\n}\n\nvar postProcessor = {\n processors: {},\n addPostProcessor(module) {\n this.processors[module.name] = module;\n },\n handle(processors, value, key, options, translator) {\n processors.forEach(processor => {\n if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);\n });\n return value;\n }\n};\n\nconst checkedLoadedFor = {};\nclass Translator extends EventEmitter {\n constructor(services) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n super();\n copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n this.logger = baseLogger.create('translator');\n }\n changeLanguage(lng) {\n if (lng) this.language = lng;\n }\n exists(key) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n interpolation: {}\n };\n if (key === undefined || key === null) {\n return false;\n }\n const resolved = this.resolve(key, options);\n return resolved && resolved.res !== undefined;\n }\n extractFromKey(key, options) {\n let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n let namespaces = options.ns || this.options.defaultNS || [];\n const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;\n const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);\n if (wouldCheckForNsInKey && !seemsNaturalLanguage) {\n const m = key.match(this.interpolator.nestingRegexp);\n if (m && m.length > 0) {\n return {\n key,\n namespaces\n };\n }\n const parts = key.split(nsSeparator);\n if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();\n key = parts.join(keySeparator);\n }\n if (typeof namespaces === 'string') namespaces = [namespaces];\n return {\n key,\n namespaces\n };\n }\n translate(keys, options, lastKey) {\n if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) {\n options = this.options.overloadTranslationOptionHandler(arguments);\n }\n if (typeof options === 'object') options = {\n ...options\n };\n if (!options) options = {};\n if (keys === undefined || keys === null) return '';\n if (!Array.isArray(keys)) keys = [String(keys)];\n const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n const {\n key,\n namespaces\n } = this.extractFromKey(keys[keys.length - 1], options);\n const namespace = namespaces[namespaces.length - 1];\n const lng = options.lng || this.language;\n const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;\n if (lng && lng.toLowerCase() === 'cimode') {\n if (appendNamespaceToCIMode) {\n const nsSeparator = options.nsSeparator || this.options.nsSeparator;\n if (returnDetails) {\n return {\n res: `${namespace}${nsSeparator}${key}`,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(options)\n };\n }\n return `${namespace}${nsSeparator}${key}`;\n }\n if (returnDetails) {\n return {\n res: key,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(options)\n };\n }\n return key;\n }\n const resolved = this.resolve(keys, options);\n let res = resolved && resolved.res;\n const resUsedKey = resolved && resolved.usedKey || key;\n const resExactUsedKey = resolved && resolved.exactUsedKey || key;\n const resType = Object.prototype.toString.apply(res);\n const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];\n const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;\n const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;\n const handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';\n if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {\n if (!options.returnObjects && !this.options.returnObjects) {\n if (!this.options.returnedObjectHandler) {\n this.logger.warn('accessing an object - but returnObjects options is not enabled!');\n }\n const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {\n ...options,\n ns: namespaces\n }) : `key '${key} (${this.language})' returned an object instead of string.`;\n if (returnDetails) {\n resolved.res = r;\n resolved.usedParams = this.getUsedParamsDetails(options);\n return resolved;\n }\n return r;\n }\n if (keySeparator) {\n const resTypeIsArray = resType === '[object Array]';\n const copy = resTypeIsArray ? [] : {};\n const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;\n for (const m in res) {\n if (Object.prototype.hasOwnProperty.call(res, m)) {\n const deepKey = `${newKeyToUse}${keySeparator}${m}`;\n copy[m] = this.translate(deepKey, {\n ...options,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n if (copy[m] === deepKey) copy[m] = res[m];\n }\n }\n res = copy;\n }\n } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {\n res = res.join(joinArrays);\n if (res) res = this.extendTranslation(res, keys, options, lastKey);\n } else {\n let usedDefault = false;\n let usedKey = false;\n const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';\n const hasDefaultValue = Translator.hasDefaultValue(options);\n const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';\n const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {\n ordinal: false\n }) : '';\n const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();\n const defaultValue = needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] || options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;\n if (!this.isValidLookup(res) && hasDefaultValue) {\n usedDefault = true;\n res = defaultValue;\n }\n if (!this.isValidLookup(res)) {\n usedKey = true;\n res = key;\n }\n const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;\n const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;\n const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;\n if (usedKey || usedDefault || updateMissing) {\n this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);\n if (keySeparator) {\n const fk = this.resolve(key, {\n ...options,\n keySeparator: false\n });\n if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');\n }\n let lngs = [];\n const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);\n if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {\n for (let i = 0; i < fallbackLngs.length; i++) {\n lngs.push(fallbackLngs[i]);\n }\n } else if (this.options.saveMissingTo === 'all') {\n lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);\n } else {\n lngs.push(options.lng || this.language);\n }\n const send = (l, k, specificDefaultValue) => {\n const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;\n if (this.options.missingKeyHandler) {\n this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);\n } else if (this.backendConnector && this.backendConnector.saveMissing) {\n this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);\n }\n this.emit('missingKey', l, namespace, k, res);\n };\n if (this.options.saveMissing) {\n if (this.options.saveMissingPlurals && needsPluralHandling) {\n lngs.forEach(language => {\n const suffixes = this.pluralResolver.getSuffixes(language, options);\n if (needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {\n suffixes.push(`${this.options.pluralSeparator}zero`);\n }\n suffixes.forEach(suffix => {\n send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);\n });\n });\n } else {\n send(lngs, key, defaultValue);\n }\n }\n }\n res = this.extendTranslation(res, keys, options, resolved, lastKey);\n if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;\n if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {\n if (this.options.compatibilityAPI !== 'v1') {\n res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined);\n } else {\n res = this.options.parseMissingKeyHandler(res);\n }\n }\n }\n if (returnDetails) {\n resolved.res = res;\n resolved.usedParams = this.getUsedParamsDetails(options);\n return resolved;\n }\n return res;\n }\n extendTranslation(res, key, options, resolved, lastKey) {\n var _this = this;\n if (this.i18nFormat && this.i18nFormat.parse) {\n res = this.i18nFormat.parse(res, {\n ...this.options.interpolation.defaultVariables,\n ...options\n }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {\n resolved\n });\n } else if (!options.skipInterpolation) {\n if (options.interpolation) this.interpolator.init({\n ...options,\n ...{\n interpolation: {\n ...this.options.interpolation,\n ...options.interpolation\n }\n }\n });\n const skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);\n let nestBef;\n if (skipOnVariables) {\n const nb = res.match(this.interpolator.nestingRegexp);\n nestBef = nb && nb.length;\n }\n let data = options.replace && typeof options.replace !== 'string' ? options.replace : options;\n if (this.options.interpolation.defaultVariables) data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n res = this.interpolator.interpolate(res, data, options.lng || this.language, options);\n if (skipOnVariables) {\n const na = res.match(this.interpolator.nestingRegexp);\n const nestAft = na && na.length;\n if (nestBef < nestAft) options.nest = false;\n }\n if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;\n if (options.nest !== false) res = this.interpolator.nest(res, function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n if (lastKey && lastKey[0] === args[0] && !options.context) {\n _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);\n return null;\n }\n return _this.translate(...args, key);\n }, options);\n if (options.interpolation) this.interpolator.reset();\n }\n const postProcess = options.postProcess || this.options.postProcess;\n const postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;\n if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {\n res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {\n i18nResolved: {\n ...resolved,\n usedParams: this.getUsedParamsDetails(options)\n },\n ...options\n } : options, this);\n }\n return res;\n }\n resolve(keys) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let found;\n let usedKey;\n let exactUsedKey;\n let usedLng;\n let usedNS;\n if (typeof keys === 'string') keys = [keys];\n keys.forEach(k => {\n if (this.isValidLookup(found)) return;\n const extracted = this.extractFromKey(k, options);\n const key = extracted.key;\n usedKey = key;\n let namespaces = extracted.namespaces;\n if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);\n const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';\n const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();\n const needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';\n const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);\n namespaces.forEach(ns => {\n if (this.isValidLookup(found)) return;\n usedNS = ns;\n if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {\n checkedLoadedFor[`${codes[0]}-${ns}`] = true;\n this.logger.warn(`key \"${usedKey}\" for languages \"${codes.join(', ')}\" won't get resolved as namespace \"${usedNS}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n }\n codes.forEach(code => {\n if (this.isValidLookup(found)) return;\n usedLng = code;\n const finalKeys = [key];\n if (this.i18nFormat && this.i18nFormat.addLookupKeys) {\n this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);\n } else {\n let pluralSuffix;\n if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);\n const zeroSuffix = `${this.options.pluralSeparator}zero`;\n const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;\n if (needsPluralHandling) {\n finalKeys.push(key + pluralSuffix);\n if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n if (needsZeroSuffixLookup) {\n finalKeys.push(key + zeroSuffix);\n }\n }\n if (needsContextHandling) {\n const contextKey = `${key}${this.options.contextSeparator}${options.context}`;\n finalKeys.push(contextKey);\n if (needsPluralHandling) {\n finalKeys.push(contextKey + pluralSuffix);\n if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n if (needsZeroSuffixLookup) {\n finalKeys.push(contextKey + zeroSuffix);\n }\n }\n }\n }\n let possibleKey;\n while (possibleKey = finalKeys.pop()) {\n if (!this.isValidLookup(found)) {\n exactUsedKey = possibleKey;\n found = this.getResource(code, ns, possibleKey, options);\n }\n }\n });\n });\n });\n return {\n res: found,\n usedKey,\n exactUsedKey,\n usedLng,\n usedNS\n };\n }\n isValidLookup(res) {\n return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');\n }\n getResource(code, ns, key) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);\n return this.resourceStore.getResource(code, ns, key, options);\n }\n getUsedParamsDetails() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];\n const useOptionsReplaceForData = options.replace && typeof options.replace !== 'string';\n let data = useOptionsReplaceForData ? options.replace : options;\n if (useOptionsReplaceForData && typeof options.count !== 'undefined') {\n data.count = options.count;\n }\n if (this.options.interpolation.defaultVariables) {\n data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n }\n if (!useOptionsReplaceForData) {\n data = {\n ...data\n };\n for (const key of optionsKeys) {\n delete data[key];\n }\n }\n return data;\n }\n static hasDefaultValue(options) {\n const prefix = 'defaultValue';\n for (const option in options) {\n if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction capitalize(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\nclass LanguageUtil {\n constructor(options) {\n this.options = options;\n this.supportedLngs = this.options.supportedLngs || false;\n this.logger = baseLogger.create('languageUtils');\n }\n getScriptPartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return null;\n const p = code.split('-');\n if (p.length === 2) return null;\n p.pop();\n if (p[p.length - 1].toLowerCase() === 'x') return null;\n return this.formatLanguageCode(p.join('-'));\n }\n getLanguagePartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return code;\n const p = code.split('-');\n return this.formatLanguageCode(p[0]);\n }\n formatLanguageCode(code) {\n if (typeof code === 'string' && code.indexOf('-') > -1) {\n const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];\n let p = code.split('-');\n if (this.options.lowerCaseLng) {\n p = p.map(part => part.toLowerCase());\n } else if (p.length === 2) {\n p[0] = p[0].toLowerCase();\n p[1] = p[1].toUpperCase();\n if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());\n } else if (p.length === 3) {\n p[0] = p[0].toLowerCase();\n if (p[1].length === 2) p[1] = p[1].toUpperCase();\n if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();\n if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());\n if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());\n }\n return p.join('-');\n }\n return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;\n }\n isSupportedCode(code) {\n if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {\n code = this.getLanguagePartFromCode(code);\n }\n return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;\n }\n getBestMatchFromCodes(codes) {\n if (!codes) return null;\n let found;\n codes.forEach(code => {\n if (found) return;\n const cleanedLng = this.formatLanguageCode(code);\n if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;\n });\n if (!found && this.options.supportedLngs) {\n codes.forEach(code => {\n if (found) return;\n const lngOnly = this.getLanguagePartFromCode(code);\n if (this.isSupportedCode(lngOnly)) return found = lngOnly;\n found = this.options.supportedLngs.find(supportedLng => {\n if (supportedLng === lngOnly) return supportedLng;\n if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;\n if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;\n if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;\n });\n });\n }\n if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];\n return found;\n }\n getFallbackCodes(fallbacks, code) {\n if (!fallbacks) return [];\n if (typeof fallbacks === 'function') fallbacks = fallbacks(code);\n if (typeof fallbacks === 'string') fallbacks = [fallbacks];\n if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;\n if (!code) return fallbacks.default || [];\n let found = fallbacks[code];\n if (!found) found = fallbacks[this.getScriptPartFromCode(code)];\n if (!found) found = fallbacks[this.formatLanguageCode(code)];\n if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];\n if (!found) found = fallbacks.default;\n return found || [];\n }\n toResolveHierarchy(code, fallbackCode) {\n const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);\n const codes = [];\n const addCode = c => {\n if (!c) return;\n if (this.isSupportedCode(c)) {\n codes.push(c);\n } else {\n this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);\n }\n };\n if (typeof code === 'string' && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {\n if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));\n if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));\n if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));\n } else if (typeof code === 'string') {\n addCode(this.formatLanguageCode(code));\n }\n fallbackCodes.forEach(fc => {\n if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));\n });\n return codes;\n }\n}\n\nlet sets = [{\n lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],\n nr: [1, 2],\n fc: 1\n}, {\n lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],\n nr: [1, 2],\n fc: 2\n}, {\n lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],\n nr: [1],\n fc: 3\n}, {\n lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],\n nr: [1, 2, 5],\n fc: 4\n}, {\n lngs: ['ar'],\n nr: [0, 1, 2, 3, 11, 100],\n fc: 5\n}, {\n lngs: ['cs', 'sk'],\n nr: [1, 2, 5],\n fc: 6\n}, {\n lngs: ['csb', 'pl'],\n nr: [1, 2, 5],\n fc: 7\n}, {\n lngs: ['cy'],\n nr: [1, 2, 3, 8],\n fc: 8\n}, {\n lngs: ['fr'],\n nr: [1, 2],\n fc: 9\n}, {\n lngs: ['ga'],\n nr: [1, 2, 3, 7, 11],\n fc: 10\n}, {\n lngs: ['gd'],\n nr: [1, 2, 3, 20],\n fc: 11\n}, {\n lngs: ['is'],\n nr: [1, 2],\n fc: 12\n}, {\n lngs: ['jv'],\n nr: [0, 1],\n fc: 13\n}, {\n lngs: ['kw'],\n nr: [1, 2, 3, 4],\n fc: 14\n}, {\n lngs: ['lt'],\n nr: [1, 2, 10],\n fc: 15\n}, {\n lngs: ['lv'],\n nr: [1, 2, 0],\n fc: 16\n}, {\n lngs: ['mk'],\n nr: [1, 2],\n fc: 17\n}, {\n lngs: ['mnk'],\n nr: [0, 1, 2],\n fc: 18\n}, {\n lngs: ['mt'],\n nr: [1, 2, 11, 20],\n fc: 19\n}, {\n lngs: ['or'],\n nr: [2, 1],\n fc: 2\n}, {\n lngs: ['ro'],\n nr: [1, 2, 20],\n fc: 20\n}, {\n lngs: ['sl'],\n nr: [5, 1, 2, 3],\n fc: 21\n}, {\n lngs: ['he', 'iw'],\n nr: [1, 2, 20, 21],\n fc: 22\n}];\nlet _rulesPluralsTypes = {\n 1: function (n) {\n return Number(n > 1);\n },\n 2: function (n) {\n return Number(n != 1);\n },\n 3: function (n) {\n return 0;\n },\n 4: function (n) {\n return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n },\n 5: function (n) {\n return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);\n },\n 6: function (n) {\n return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);\n },\n 7: function (n) {\n return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n },\n 8: function (n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);\n },\n 9: function (n) {\n return Number(n >= 2);\n },\n 10: function (n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);\n },\n 11: function (n) {\n return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);\n },\n 12: function (n) {\n return Number(n % 10 != 1 || n % 100 == 11);\n },\n 13: function (n) {\n return Number(n !== 0);\n },\n 14: function (n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);\n },\n 15: function (n) {\n return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n },\n 16: function (n) {\n return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);\n },\n 17: function (n) {\n return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);\n },\n 18: function (n) {\n return Number(n == 0 ? 0 : n == 1 ? 1 : 2);\n },\n 19: function (n) {\n return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);\n },\n 20: function (n) {\n return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);\n },\n 21: function (n) {\n return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);\n },\n 22: function (n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);\n }\n};\nconst nonIntlVersions = ['v1', 'v2', 'v3'];\nconst intlVersions = ['v4'];\nconst suffixesOrder = {\n zero: 0,\n one: 1,\n two: 2,\n few: 3,\n many: 4,\n other: 5\n};\nfunction createRules() {\n const rules = {};\n sets.forEach(set => {\n set.lngs.forEach(l => {\n rules[l] = {\n numbers: set.nr,\n plurals: _rulesPluralsTypes[set.fc]\n };\n });\n });\n return rules;\n}\nclass PluralResolver {\n constructor(languageUtils) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n this.languageUtils = languageUtils;\n this.options = options;\n this.logger = baseLogger.create('pluralResolver');\n if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) {\n this.options.compatibilityJSON = 'v3';\n this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');\n }\n this.rules = createRules();\n }\n addRule(lng, obj) {\n this.rules[lng] = obj;\n }\n getRule(code) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (this.shouldUseIntlApi()) {\n try {\n return new Intl.PluralRules(getCleanedCode(code === 'dev' ? 'en' : code), {\n type: options.ordinal ? 'ordinal' : 'cardinal'\n });\n } catch (err) {\n return;\n }\n }\n return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];\n }\n needsPlural(code) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const rule = this.getRule(code, options);\n if (this.shouldUseIntlApi()) {\n return rule && rule.resolvedOptions().pluralCategories.length > 1;\n }\n return rule && rule.numbers.length > 1;\n }\n getPluralFormsOfKey(code, key) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);\n }\n getSuffixes(code) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n const rule = this.getRule(code, options);\n if (!rule) {\n return [];\n }\n if (this.shouldUseIntlApi()) {\n return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);\n }\n return rule.numbers.map(number => this.getSuffix(code, number, options));\n }\n getSuffix(code, count) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n const rule = this.getRule(code, options);\n if (rule) {\n if (this.shouldUseIntlApi()) {\n return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;\n }\n return this.getSuffixRetroCompatible(rule, count);\n }\n this.logger.warn(`no plural rule found for: ${code}`);\n return '';\n }\n getSuffixRetroCompatible(rule, count) {\n const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));\n let suffix = rule.numbers[idx];\n if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {\n if (suffix === 2) {\n suffix = 'plural';\n } else if (suffix === 1) {\n suffix = '';\n }\n }\n const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();\n if (this.options.compatibilityJSON === 'v1') {\n if (suffix === 1) return '';\n if (typeof suffix === 'number') return `_plural_${suffix.toString()}`;\n return returnSuffix();\n } else if (this.options.compatibilityJSON === 'v2') {\n return returnSuffix();\n } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {\n return returnSuffix();\n }\n return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();\n }\n shouldUseIntlApi() {\n return !nonIntlVersions.includes(this.options.compatibilityJSON);\n }\n}\n\nfunction deepFindWithDefaults(data, defaultData, key) {\n let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';\n let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n let path = getPathWithDefaults(data, defaultData, key);\n if (!path && ignoreJSONStructure && typeof key === 'string') {\n path = deepFind(data, key, keySeparator);\n if (path === undefined) path = deepFind(defaultData, key, keySeparator);\n }\n return path;\n}\nclass Interpolator {\n constructor() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.logger = baseLogger.create('interpolator');\n this.options = options;\n this.format = options.interpolation && options.interpolation.format || (value => value);\n this.init(options);\n }\n init() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (!options.interpolation) options.interpolation = {\n escapeValue: true\n };\n const iOpts = options.interpolation;\n this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;\n this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;\n this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;\n this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';\n this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';\n this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';\n this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';\n this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';\n this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');\n this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');\n this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';\n this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;\n this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;\n this.resetRegExp();\n }\n reset() {\n if (this.options) this.init(this.options);\n }\n resetRegExp() {\n const getOrResetRegExp = (existingRegExp, pattern) => {\n if (existingRegExp && existingRegExp.source === pattern) {\n existingRegExp.lastIndex = 0;\n return existingRegExp;\n }\n return new RegExp(pattern, 'g');\n };\n this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);\n this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);\n this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);\n }\n interpolate(str, data, lng, options) {\n let match;\n let value;\n let replaces;\n const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};\n function regexSafe(val) {\n return val.replace(/\\$/g, '$$$$');\n }\n const handleFormat = key => {\n if (key.indexOf(this.formatSeparator) < 0) {\n const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);\n return this.alwaysFormat ? this.format(path, undefined, lng, {\n ...options,\n ...data,\n interpolationkey: key\n }) : path;\n }\n const p = key.split(this.formatSeparator);\n const k = p.shift().trim();\n const f = p.join(this.formatSeparator).trim();\n return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {\n ...options,\n ...data,\n interpolationkey: k\n });\n };\n this.resetRegExp();\n const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;\n const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;\n const todos = [{\n regex: this.regexpUnescape,\n safeValue: val => regexSafe(val)\n }, {\n regex: this.regexp,\n safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)\n }];\n todos.forEach(todo => {\n replaces = 0;\n while (match = todo.regex.exec(str)) {\n const matchedVar = match[1].trim();\n value = handleFormat(matchedVar);\n if (value === undefined) {\n if (typeof missingInterpolationHandler === 'function') {\n const temp = missingInterpolationHandler(str, match, options);\n value = typeof temp === 'string' ? temp : '';\n } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {\n value = '';\n } else if (skipOnVariables) {\n value = match[0];\n continue;\n } else {\n this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);\n value = '';\n }\n } else if (typeof value !== 'string' && !this.useRawValueToEscape) {\n value = makeString(value);\n }\n const safeValue = todo.safeValue(value);\n str = str.replace(match[0], safeValue);\n if (skipOnVariables) {\n todo.regex.lastIndex += value.length;\n todo.regex.lastIndex -= match[0].length;\n } else {\n todo.regex.lastIndex = 0;\n }\n replaces++;\n if (replaces >= this.maxReplaces) {\n break;\n }\n }\n });\n return str;\n }\n nest(str, fc) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n let match;\n let value;\n let clonedOptions;\n function handleHasOptions(key, inheritedOptions) {\n const sep = this.nestingOptionsSeparator;\n if (key.indexOf(sep) < 0) return key;\n const c = key.split(new RegExp(`${sep}[ ]*{`));\n let optionsString = `{${c[1]}`;\n key = c[0];\n optionsString = this.interpolate(optionsString, clonedOptions);\n const matchedSingleQuotes = optionsString.match(/'/g);\n const matchedDoubleQuotes = optionsString.match(/\"/g);\n if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {\n optionsString = optionsString.replace(/'/g, '\"');\n }\n try {\n clonedOptions = JSON.parse(optionsString);\n if (inheritedOptions) clonedOptions = {\n ...inheritedOptions,\n ...clonedOptions\n };\n } catch (e) {\n this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);\n return `${key}${sep}${optionsString}`;\n }\n if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;\n return key;\n }\n while (match = this.nestingRegexp.exec(str)) {\n let formatters = [];\n clonedOptions = {\n ...options\n };\n clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;\n clonedOptions.applyPostProcessor = false;\n delete clonedOptions.defaultValue;\n let doReduce = false;\n if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {\n const r = match[1].split(this.formatSeparator).map(elem => elem.trim());\n match[1] = r.shift();\n formatters = r;\n doReduce = true;\n }\n value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);\n if (value && match[0] === str && typeof value !== 'string') return value;\n if (typeof value !== 'string') value = makeString(value);\n if (!value) {\n this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);\n value = '';\n }\n if (doReduce) {\n value = formatters.reduce((v, f) => this.format(v, f, options.lng, {\n ...options,\n interpolationkey: match[1].trim()\n }), value.trim());\n }\n str = str.replace(match[0], value);\n this.regexp.lastIndex = 0;\n }\n return str;\n }\n}\n\nfunction parseFormatStr(formatStr) {\n let formatName = formatStr.toLowerCase().trim();\n const formatOptions = {};\n if (formatStr.indexOf('(') > -1) {\n const p = formatStr.split('(');\n formatName = p[0].toLowerCase().trim();\n const optStr = p[1].substring(0, p[1].length - 1);\n if (formatName === 'currency' && optStr.indexOf(':') < 0) {\n if (!formatOptions.currency) formatOptions.currency = optStr.trim();\n } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {\n if (!formatOptions.range) formatOptions.range = optStr.trim();\n } else {\n const opts = optStr.split(';');\n opts.forEach(opt => {\n if (!opt) return;\n const [key, ...rest] = opt.split(':');\n const val = rest.join(':').trim().replace(/^'+|'+$/g, '');\n if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;\n if (val === 'false') formatOptions[key.trim()] = false;\n if (val === 'true') formatOptions[key.trim()] = true;\n if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);\n });\n }\n }\n return {\n formatName,\n formatOptions\n };\n}\nfunction createCachedFormatter(fn) {\n const cache = {};\n return function invokeFormatter(val, lng, options) {\n const key = lng + JSON.stringify(options);\n let formatter = cache[key];\n if (!formatter) {\n formatter = fn(getCleanedCode(lng), options);\n cache[key] = formatter;\n }\n return formatter(val);\n };\n}\nclass Formatter {\n constructor() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.logger = baseLogger.create('formatter');\n this.options = options;\n this.formats = {\n number: createCachedFormatter((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n currency: createCachedFormatter((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt,\n style: 'currency'\n });\n return val => formatter.format(val);\n }),\n datetime: createCachedFormatter((lng, opt) => {\n const formatter = new Intl.DateTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n relativetime: createCachedFormatter((lng, opt) => {\n const formatter = new Intl.RelativeTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val, opt.range || 'day');\n }),\n list: createCachedFormatter((lng, opt) => {\n const formatter = new Intl.ListFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n })\n };\n this.init(options);\n }\n init(services) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n interpolation: {}\n };\n const iOpts = options.interpolation;\n this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';\n }\n add(name, fc) {\n this.formats[name.toLowerCase().trim()] = fc;\n }\n addCached(name, fc) {\n this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);\n }\n format(value, format, lng) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n const formats = format.split(this.formatSeparator);\n const result = formats.reduce((mem, f) => {\n const {\n formatName,\n formatOptions\n } = parseFormatStr(f);\n if (this.formats[formatName]) {\n let formatted = mem;\n try {\n const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};\n const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;\n formatted = this.formats[formatName](mem, l, {\n ...formatOptions,\n ...options,\n ...valOptions\n });\n } catch (error) {\n this.logger.warn(error);\n }\n return formatted;\n } else {\n this.logger.warn(`there was no format function for ${formatName}`);\n }\n return mem;\n }, value);\n return result;\n }\n}\n\nfunction removePending(q, name) {\n if (q.pending[name] !== undefined) {\n delete q.pending[name];\n q.pendingCount--;\n }\n}\nclass Connector extends EventEmitter {\n constructor(backend, store, services) {\n let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n super();\n this.backend = backend;\n this.store = store;\n this.services = services;\n this.languageUtils = services.languageUtils;\n this.options = options;\n this.logger = baseLogger.create('backendConnector');\n this.waitingReads = [];\n this.maxParallelReads = options.maxParallelReads || 10;\n this.readingCalls = 0;\n this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;\n this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;\n this.state = {};\n this.queue = [];\n if (this.backend && this.backend.init) {\n this.backend.init(services, options.backend, options);\n }\n }\n queueLoad(languages, namespaces, options, callback) {\n const toLoad = {};\n const pending = {};\n const toLoadLanguages = {};\n const toLoadNamespaces = {};\n languages.forEach(lng => {\n let hasAllNamespaces = true;\n namespaces.forEach(ns => {\n const name = `${lng}|${ns}`;\n if (!options.reload && this.store.hasResourceBundle(lng, ns)) {\n this.state[name] = 2;\n } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {\n if (pending[name] === undefined) pending[name] = true;\n } else {\n this.state[name] = 1;\n hasAllNamespaces = false;\n if (pending[name] === undefined) pending[name] = true;\n if (toLoad[name] === undefined) toLoad[name] = true;\n if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;\n }\n });\n if (!hasAllNamespaces) toLoadLanguages[lng] = true;\n });\n if (Object.keys(toLoad).length || Object.keys(pending).length) {\n this.queue.push({\n pending,\n pendingCount: Object.keys(pending).length,\n loaded: {},\n errors: [],\n callback\n });\n }\n return {\n toLoad: Object.keys(toLoad),\n pending: Object.keys(pending),\n toLoadLanguages: Object.keys(toLoadLanguages),\n toLoadNamespaces: Object.keys(toLoadNamespaces)\n };\n }\n loaded(name, err, data) {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n if (err) this.emit('failedLoading', lng, ns, err);\n if (data) {\n this.store.addResourceBundle(lng, ns, data, undefined, undefined, {\n skipCopy: true\n });\n }\n this.state[name] = err ? -1 : 2;\n const loaded = {};\n this.queue.forEach(q => {\n pushPath(q.loaded, [lng], ns);\n removePending(q, name);\n if (err) q.errors.push(err);\n if (q.pendingCount === 0 && !q.done) {\n Object.keys(q.loaded).forEach(l => {\n if (!loaded[l]) loaded[l] = {};\n const loadedKeys = q.loaded[l];\n if (loadedKeys.length) {\n loadedKeys.forEach(n => {\n if (loaded[l][n] === undefined) loaded[l][n] = true;\n });\n }\n });\n q.done = true;\n if (q.errors.length) {\n q.callback(q.errors);\n } else {\n q.callback();\n }\n }\n });\n this.emit('loaded', loaded);\n this.queue = this.queue.filter(q => !q.done);\n }\n read(lng, ns, fcName) {\n let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;\n let callback = arguments.length > 5 ? arguments[5] : undefined;\n if (!lng.length) return callback(null, {});\n if (this.readingCalls >= this.maxParallelReads) {\n this.waitingReads.push({\n lng,\n ns,\n fcName,\n tried,\n wait,\n callback\n });\n return;\n }\n this.readingCalls++;\n const resolver = (err, data) => {\n this.readingCalls--;\n if (this.waitingReads.length > 0) {\n const next = this.waitingReads.shift();\n this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);\n }\n if (err && data && tried < this.maxRetries) {\n setTimeout(() => {\n this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);\n }, wait);\n return;\n }\n callback(err, data);\n };\n const fc = this.backend[fcName].bind(this.backend);\n if (fc.length === 2) {\n try {\n const r = fc(lng, ns);\n if (r && typeof r.then === 'function') {\n r.then(data => resolver(null, data)).catch(resolver);\n } else {\n resolver(null, r);\n }\n } catch (err) {\n resolver(err);\n }\n return;\n }\n return fc(lng, ns, resolver);\n }\n prepareLoading(languages, namespaces) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n let callback = arguments.length > 3 ? arguments[3] : undefined;\n if (!this.backend) {\n this.logger.warn('No backend was added via i18next.use. Will not load resources.');\n return callback && callback();\n }\n if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);\n if (typeof namespaces === 'string') namespaces = [namespaces];\n const toLoad = this.queueLoad(languages, namespaces, options, callback);\n if (!toLoad.toLoad.length) {\n if (!toLoad.pending.length) callback();\n return null;\n }\n toLoad.toLoad.forEach(name => {\n this.loadOne(name);\n });\n }\n load(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {}, callback);\n }\n reload(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {\n reload: true\n }, callback);\n }\n loadOne(name) {\n let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n this.read(lng, ns, 'read', undefined, undefined, (err, data) => {\n if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);\n if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);\n this.loaded(name, err, data);\n });\n }\n saveMissing(languages, namespace, key, fallbackValue, isUpdate) {\n let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};\n let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {};\n if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {\n this.logger.warn(`did not save key \"${key}\" as the namespace \"${namespace}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n return;\n }\n if (key === undefined || key === null || key === '') return;\n if (this.backend && this.backend.create) {\n const opts = {\n ...options,\n isUpdate\n };\n const fc = this.backend.create.bind(this.backend);\n if (fc.length < 6) {\n try {\n let r;\n if (fc.length === 5) {\n r = fc(languages, namespace, key, fallbackValue, opts);\n } else {\n r = fc(languages, namespace, key, fallbackValue);\n }\n if (r && typeof r.then === 'function') {\n r.then(data => clb(null, data)).catch(clb);\n } else {\n clb(null, r);\n }\n } catch (err) {\n clb(err);\n }\n } else {\n fc(languages, namespace, key, fallbackValue, clb, opts);\n }\n }\n if (!languages || !languages[0]) return;\n this.store.addResource(languages[0], namespace, key, fallbackValue);\n }\n}\n\nfunction get() {\n return {\n debug: false,\n initImmediate: true,\n ns: ['translation'],\n defaultNS: ['translation'],\n fallbackLng: ['dev'],\n fallbackNS: false,\n supportedLngs: false,\n nonExplicitSupportedLngs: false,\n load: 'all',\n preload: false,\n simplifyPluralSuffix: true,\n keySeparator: '.',\n nsSeparator: ':',\n pluralSeparator: '_',\n contextSeparator: '_',\n partialBundledLanguages: false,\n saveMissing: false,\n updateMissing: false,\n saveMissingTo: 'fallback',\n saveMissingPlurals: true,\n missingKeyHandler: false,\n missingInterpolationHandler: false,\n postProcess: false,\n postProcessPassResolved: false,\n returnNull: false,\n returnEmptyString: true,\n returnObjects: false,\n joinArrays: false,\n returnedObjectHandler: false,\n parseMissingKeyHandler: false,\n appendNamespaceToMissingKey: false,\n appendNamespaceToCIMode: false,\n overloadTranslationOptionHandler: function handle(args) {\n let ret = {};\n if (typeof args[1] === 'object') ret = args[1];\n if (typeof args[1] === 'string') ret.defaultValue = args[1];\n if (typeof args[2] === 'string') ret.tDescription = args[2];\n if (typeof args[2] === 'object' || typeof args[3] === 'object') {\n const options = args[3] || args[2];\n Object.keys(options).forEach(key => {\n ret[key] = options[key];\n });\n }\n return ret;\n },\n interpolation: {\n escapeValue: true,\n format: value => value,\n prefix: '{{',\n suffix: '}}',\n formatSeparator: ',',\n unescapePrefix: '-',\n nestingPrefix: '$t(',\n nestingSuffix: ')',\n nestingOptionsSeparator: ',',\n maxReplaces: 1000,\n skipOnVariables: true\n }\n };\n}\nfunction transformOptions(options) {\n if (typeof options.ns === 'string') options.ns = [options.ns];\n if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];\n if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];\n if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {\n options.supportedLngs = options.supportedLngs.concat(['cimode']);\n }\n return options;\n}\n\nfunction noop() {}\nfunction bindMemberFunctions(inst) {\n const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));\n mems.forEach(mem => {\n if (typeof inst[mem] === 'function') {\n inst[mem] = inst[mem].bind(inst);\n }\n });\n}\nclass I18n extends EventEmitter {\n constructor() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let callback = arguments.length > 1 ? arguments[1] : undefined;\n super();\n this.options = transformOptions(options);\n this.services = {};\n this.logger = baseLogger;\n this.modules = {\n external: []\n };\n bindMemberFunctions(this);\n if (callback && !this.isInitialized && !options.isClone) {\n if (!this.options.initImmediate) {\n this.init(options, callback);\n return this;\n }\n setTimeout(() => {\n this.init(options, callback);\n }, 0);\n }\n }\n init() {\n var _this = this;\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let callback = arguments.length > 1 ? arguments[1] : undefined;\n this.isInitializing = true;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (!options.defaultNS && options.defaultNS !== false && options.ns) {\n if (typeof options.ns === 'string') {\n options.defaultNS = options.ns;\n } else if (options.ns.indexOf('translation') < 0) {\n options.defaultNS = options.ns[0];\n }\n }\n const defOpts = get();\n this.options = {\n ...defOpts,\n ...this.options,\n ...transformOptions(options)\n };\n if (this.options.compatibilityAPI !== 'v1') {\n this.options.interpolation = {\n ...defOpts.interpolation,\n ...this.options.interpolation\n };\n }\n if (options.keySeparator !== undefined) {\n this.options.userDefinedKeySeparator = options.keySeparator;\n }\n if (options.nsSeparator !== undefined) {\n this.options.userDefinedNsSeparator = options.nsSeparator;\n }\n function createClassOnDemand(ClassOrObject) {\n if (!ClassOrObject) return null;\n if (typeof ClassOrObject === 'function') return new ClassOrObject();\n return ClassOrObject;\n }\n if (!this.options.isClone) {\n if (this.modules.logger) {\n baseLogger.init(createClassOnDemand(this.modules.logger), this.options);\n } else {\n baseLogger.init(null, this.options);\n }\n let formatter;\n if (this.modules.formatter) {\n formatter = this.modules.formatter;\n } else if (typeof Intl !== 'undefined') {\n formatter = Formatter;\n }\n const lu = new LanguageUtil(this.options);\n this.store = new ResourceStore(this.options.resources, this.options);\n const s = this.services;\n s.logger = baseLogger;\n s.resourceStore = this.store;\n s.languageUtils = lu;\n s.pluralResolver = new PluralResolver(lu, {\n prepend: this.options.pluralSeparator,\n compatibilityJSON: this.options.compatibilityJSON,\n simplifyPluralSuffix: this.options.simplifyPluralSuffix\n });\n if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {\n s.formatter = createClassOnDemand(formatter);\n s.formatter.init(s, this.options);\n this.options.interpolation.format = s.formatter.format.bind(s.formatter);\n }\n s.interpolator = new Interpolator(this.options);\n s.utils = {\n hasLoadedNamespace: this.hasLoadedNamespace.bind(this)\n };\n s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);\n s.backendConnector.on('*', function (event) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n _this.emit(event, ...args);\n });\n if (this.modules.languageDetector) {\n s.languageDetector = createClassOnDemand(this.modules.languageDetector);\n if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);\n }\n if (this.modules.i18nFormat) {\n s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);\n if (s.i18nFormat.init) s.i18nFormat.init(this);\n }\n this.translator = new Translator(this.services, this.options);\n this.translator.on('*', function (event) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n _this.emit(event, ...args);\n });\n this.modules.external.forEach(m => {\n if (m.init) m.init(this);\n });\n }\n this.format = this.options.interpolation.format;\n if (!callback) callback = noop;\n if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {\n const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];\n }\n if (!this.services.languageDetector && !this.options.lng) {\n this.logger.warn('init: no languageDetector is used and no lng is defined');\n }\n const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];\n storeApi.forEach(fcName => {\n this[fcName] = function () {\n return _this.store[fcName](...arguments);\n };\n });\n const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];\n storeApiChained.forEach(fcName => {\n this[fcName] = function () {\n _this.store[fcName](...arguments);\n return _this;\n };\n });\n const deferred = defer();\n const load = () => {\n const finish = (err, t) => {\n this.isInitializing = false;\n if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');\n this.isInitialized = true;\n if (!this.options.isClone) this.logger.log('initialized', this.options);\n this.emit('initialized', this.options);\n deferred.resolve(t);\n callback(err, t);\n };\n if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this));\n this.changeLanguage(this.options.lng, finish);\n };\n if (this.options.resources || !this.options.initImmediate) {\n load();\n } else {\n setTimeout(load, 0);\n }\n return deferred;\n }\n loadResources(language) {\n let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;\n let usedCallback = callback;\n const usedLng = typeof language === 'string' ? language : this.language;\n if (typeof language === 'function') usedCallback = language;\n if (!this.options.resources || this.options.partialBundledLanguages) {\n if (usedLng && usedLng.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();\n const toLoad = [];\n const append = lng => {\n if (!lng) return;\n if (lng === 'cimode') return;\n const lngs = this.services.languageUtils.toResolveHierarchy(lng);\n lngs.forEach(l => {\n if (l === 'cimode') return;\n if (toLoad.indexOf(l) < 0) toLoad.push(l);\n });\n };\n if (!usedLng) {\n const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n fallbacks.forEach(l => append(l));\n } else {\n append(usedLng);\n }\n if (this.options.preload) {\n this.options.preload.forEach(l => append(l));\n }\n this.services.backendConnector.load(toLoad, this.options.ns, e => {\n if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);\n usedCallback(e);\n });\n } else {\n usedCallback(null);\n }\n }\n reloadResources(lngs, ns, callback) {\n const deferred = defer();\n if (!lngs) lngs = this.languages;\n if (!ns) ns = this.options.ns;\n if (!callback) callback = noop;\n this.services.backendConnector.reload(lngs, ns, err => {\n deferred.resolve();\n callback(err);\n });\n return deferred;\n }\n use(module) {\n if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');\n if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');\n if (module.type === 'backend') {\n this.modules.backend = module;\n }\n if (module.type === 'logger' || module.log && module.warn && module.error) {\n this.modules.logger = module;\n }\n if (module.type === 'languageDetector') {\n this.modules.languageDetector = module;\n }\n if (module.type === 'i18nFormat') {\n this.modules.i18nFormat = module;\n }\n if (module.type === 'postProcessor') {\n postProcessor.addPostProcessor(module);\n }\n if (module.type === 'formatter') {\n this.modules.formatter = module;\n }\n if (module.type === '3rdParty') {\n this.modules.external.push(module);\n }\n return this;\n }\n setResolvedLanguage(l) {\n if (!l || !this.languages) return;\n if (['cimode', 'dev'].indexOf(l) > -1) return;\n for (let li = 0; li < this.languages.length; li++) {\n const lngInLngs = this.languages[li];\n if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;\n if (this.store.hasLanguageSomeTranslations(lngInLngs)) {\n this.resolvedLanguage = lngInLngs;\n break;\n }\n }\n }\n changeLanguage(lng, callback) {\n var _this2 = this;\n this.isLanguageChangingTo = lng;\n const deferred = defer();\n this.emit('languageChanging', lng);\n const setLngProps = l => {\n this.language = l;\n this.languages = this.services.languageUtils.toResolveHierarchy(l);\n this.resolvedLanguage = undefined;\n this.setResolvedLanguage(l);\n };\n const done = (err, l) => {\n if (l) {\n setLngProps(l);\n this.translator.changeLanguage(l);\n this.isLanguageChangingTo = undefined;\n this.emit('languageChanged', l);\n this.logger.log('languageChanged', l);\n } else {\n this.isLanguageChangingTo = undefined;\n }\n deferred.resolve(function () {\n return _this2.t(...arguments);\n });\n if (callback) callback(err, function () {\n return _this2.t(...arguments);\n });\n };\n const setLng = lngs => {\n if (!lng && !lngs && this.services.languageDetector) lngs = [];\n const l = typeof lngs === 'string' ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);\n if (l) {\n if (!this.language) {\n setLngProps(l);\n }\n if (!this.translator.language) this.translator.changeLanguage(l);\n if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);\n }\n this.loadResources(l, err => {\n done(err, l);\n });\n };\n if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {\n setLng(this.services.languageDetector.detect());\n } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {\n if (this.services.languageDetector.detect.length === 0) {\n this.services.languageDetector.detect().then(setLng);\n } else {\n this.services.languageDetector.detect(setLng);\n }\n } else {\n setLng(lng);\n }\n return deferred;\n }\n getFixedT(lng, ns, keyPrefix) {\n var _this3 = this;\n const fixedT = function (key, opts) {\n let options;\n if (typeof opts !== 'object') {\n for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {\n rest[_key3 - 2] = arguments[_key3];\n }\n options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));\n } else {\n options = {\n ...opts\n };\n }\n options.lng = options.lng || fixedT.lng;\n options.lngs = options.lngs || fixedT.lngs;\n options.ns = options.ns || fixedT.ns;\n options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;\n const keySeparator = _this3.options.keySeparator || '.';\n let resultKey;\n if (options.keyPrefix && Array.isArray(key)) {\n resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`);\n } else {\n resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;\n }\n return _this3.t(resultKey, options);\n };\n if (typeof lng === 'string') {\n fixedT.lng = lng;\n } else {\n fixedT.lngs = lng;\n }\n fixedT.ns = ns;\n fixedT.keyPrefix = keyPrefix;\n return fixedT;\n }\n t() {\n return this.translator && this.translator.translate(...arguments);\n }\n exists() {\n return this.translator && this.translator.exists(...arguments);\n }\n setDefaultNamespace(ns) {\n this.options.defaultNS = ns;\n }\n hasLoadedNamespace(ns) {\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (!this.isInitialized) {\n this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);\n return false;\n }\n if (!this.languages || !this.languages.length) {\n this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);\n return false;\n }\n const lng = options.lng || this.resolvedLanguage || this.languages[0];\n const fallbackLng = this.options ? this.options.fallbackLng : false;\n const lastLng = this.languages[this.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n const loadNotPending = (l, n) => {\n const loadState = this.services.backendConnector.state[`${l}|${n}`];\n return loadState === -1 || loadState === 2;\n };\n if (options.precheck) {\n const preResult = options.precheck(this, loadNotPending);\n if (preResult !== undefined) return preResult;\n }\n if (this.hasResourceBundle(lng, ns)) return true;\n if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n }\n loadNamespaces(ns, callback) {\n const deferred = defer();\n if (!this.options.ns) {\n if (callback) callback();\n return Promise.resolve();\n }\n if (typeof ns === 'string') ns = [ns];\n ns.forEach(n => {\n if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);\n });\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n loadLanguages(lngs, callback) {\n const deferred = defer();\n if (typeof lngs === 'string') lngs = [lngs];\n const preloaded = this.options.preload || [];\n const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));\n if (!newLngs.length) {\n if (callback) callback();\n return Promise.resolve();\n }\n this.options.preload = preloaded.concat(newLngs);\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n dir(lng) {\n if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);\n if (!lng) return 'rtl';\n const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];\n const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());\n return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';\n }\n static createInstance() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let callback = arguments.length > 1 ? arguments[1] : undefined;\n return new I18n(options, callback);\n }\n cloneInstance() {\n let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;\n const forkResourceStore = options.forkResourceStore;\n if (forkResourceStore) delete options.forkResourceStore;\n const mergedOptions = {\n ...this.options,\n ...options,\n ...{\n isClone: true\n }\n };\n const clone = new I18n(mergedOptions);\n if (options.debug !== undefined || options.prefix !== undefined) {\n clone.logger = clone.logger.clone(options);\n }\n const membersToCopy = ['store', 'services', 'language'];\n membersToCopy.forEach(m => {\n clone[m] = this[m];\n });\n clone.services = {\n ...this.services\n };\n clone.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n if (forkResourceStore) {\n clone.store = new ResourceStore(this.store.data, mergedOptions);\n clone.services.resourceStore = clone.store;\n }\n clone.translator = new Translator(clone.services, mergedOptions);\n clone.translator.on('*', function (event) {\n for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n args[_key4 - 1] = arguments[_key4];\n }\n clone.emit(event, ...args);\n });\n clone.init(mergedOptions, callback);\n clone.translator.options = mergedOptions;\n clone.translator.backendConnector.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n return clone;\n }\n toJSON() {\n return {\n options: this.options,\n store: this.store,\n language: this.language,\n languages: this.languages,\n resolvedLanguage: this.resolvedLanguage\n };\n }\n}\nconst instance = I18n.createInstance();\ninstance.createInstance = I18n.createInstance;\n\nconst createInstance = instance.createInstance;\nconst dir = instance.dir;\nconst init = instance.init;\nconst loadResources = instance.loadResources;\nconst reloadResources = instance.reloadResources;\nconst use = instance.use;\nconst changeLanguage = instance.changeLanguage;\nconst getFixedT = instance.getFixedT;\nconst t = instance.t;\nconst exists = instance.exists;\nconst setDefaultNamespace = instance.setDefaultNamespace;\nconst hasLoadedNamespace = instance.hasLoadedNamespace;\nconst loadNamespaces = instance.loadNamespaces;\nconst loadLanguages = instance.loadLanguages;\n\nexport { changeLanguage, createInstance, instance as default, dir, exists, getFixedT, hasLoadedNamespace, init, loadLanguages, loadNamespaces, loadResources, reloadResources, setDefaultNamespace, t, use };\n","const isObject = (obj: any) => obj && typeof obj === 'object';\n\nexport const deepMerge = (...objects: any[]) => {\n return objects.reduce((prev, obj) => {\n for (const key in obj) {\n if (isObject(prev[key]) && isObject(obj[key])) {\n prev[key] = deepMerge(prev[key], obj[key]);\n } else {\n prev[key] = obj[key];\n }\n }\n return prev;\n }, {});\n};\n","export const currencyExtendedFormatter = (\n lng: string | undefined,\n options: any,\n) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...options,\n style: 'currency',\n });\n return (value: any) => {\n if (value > 0 && value < 0.01) {\n return `<${formatter.format(0.01)}`;\n }\n return formatter.format(value);\n };\n};\n","/**\n * We use <0.01% for both small positive and negative changes to keep it simple and clear, focusing on minimal impact rather than direction.\n * Examples:\n * +0.007% -> <0.01%\n * -0.003% -> <0.01%\n */\nexport const percentFormatter = (lng: string | undefined, options: any) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...options,\n style: 'percent',\n });\n return (value: any) => {\n if ((value > 0 && value < 0.0001) || (value < 0 && value > -0.0001)) {\n return `<${formatter.format(0.0001)}`;\n }\n return formatter.format(value);\n };\n};\n","import type { i18n } from 'i18next';\nimport { createInstance } from 'i18next';\nimport { useMemo } from 'react';\nimport { I18nextProvider } from 'react-i18next';\nimport * as supportedLanguages from '../../i18n/index.js';\nimport { useSettings } from '../../stores/settings/useSettings.js';\nimport { deepMerge } from '../../utils/deepMerge.js';\nimport { isItemAllowed } from '../../utils/item.js';\nimport { useWidgetConfig } from '../WidgetProvider/WidgetProvider.js';\nimport { currencyExtendedFormatter } from './currencyExtendedFormatter.js';\nimport { percentFormatter } from './percentFormatter.js';\nimport type { LanguageKey, LanguageTranslationResources } from './types.js';\n\nexport const I18nProvider: React.FC = ({\n children,\n}) => {\n const { languageResources, languages } = useWidgetConfig();\n const { language } = useSettings(['language']);\n\n const i18n = useMemo(() => {\n let resources = (Object.keys(supportedLanguages) as LanguageKey[])\n .filter((lng) => isItemAllowed(lng, languages))\n .reduce((resources, lng) => {\n resources[lng] = {\n translation: languageResources?.[lng]\n ? (deepMerge(\n supportedLanguages[lng],\n languageResources[lng],\n ) as any)\n : supportedLanguages[lng],\n };\n return resources;\n }, {} as LanguageTranslationResources);\n\n if (languageResources) {\n resources = Object.keys(languageResources).reduce((resources, lng) => {\n if (!resources[lng]) {\n resources[lng] = {\n translation: languageResources[lng as LanguageKey]!,\n };\n }\n return resources;\n }, resources);\n }\n\n let i18n = createInstance({\n lng: languages?.default || language,\n fallbackLng: resources.en\n ? 'en'\n : languages?.default ||\n languages?.allow?.[0] ||\n Object.keys(resources)?.[0],\n lowerCaseLng: true,\n interpolation: {\n escapeValue: false,\n },\n resources,\n detection: {\n caches: [],\n },\n returnEmptyString: false,\n });\n\n i18n.init();\n\n i18n.services.formatter?.addCached(\n 'currencyExt',\n currencyExtendedFormatter,\n );\n i18n.services.formatter?.addCached('percent', percentFormatter);\n\n return i18n;\n }, [language, languageResources, languages]);\n\n return {children};\n};\n","import * as React from 'react';\nconst ThemeContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== 'production') {\n ThemeContext.displayName = 'ThemeContext';\n}\nexport default ThemeContext;","import * as React from 'react';\nimport ThemeContext from './ThemeContext';\nexport default function useTheme() {\n const theme = React.useContext(ThemeContext);\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n return theme;\n}","const hasSymbol = typeof Symbol === 'function' && Symbol.for;\nexport default hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__';","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { exactProp } from '@mui/utils';\nimport ThemeContext from '../useTheme/ThemeContext';\nimport useTheme from '../useTheme';\nimport nested from './nested';\n\n// To support composition of theme.\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction mergeOuterLocalTheme(outerTheme, localTheme) {\n if (typeof localTheme === 'function') {\n const mergedTheme = localTheme(outerTheme);\n if (process.env.NODE_ENV !== 'production') {\n if (!mergedTheme) {\n console.error(['MUI: You should return an object from your theme function, i.e.', ' ({})} />'].join('\\n'));\n }\n }\n return mergedTheme;\n }\n return _extends({}, outerTheme, localTheme);\n}\n\n/**\n * This component takes a `theme` prop.\n * It makes the `theme` available down the React tree thanks to React context.\n * This component should preferably be used at **the root of your component tree**.\n */\nfunction ThemeProvider(props) {\n const {\n children,\n theme: localTheme\n } = props;\n const outerTheme = useTheme();\n if (process.env.NODE_ENV !== 'production') {\n if (outerTheme === null && typeof localTheme === 'function') {\n console.error(['MUI: You are providing a theme function prop to the ThemeProvider component:', ' outerTheme} />', '', 'However, no outer theme is present.', 'Make sure a theme is already injected higher in the React tree ' + 'or provide a theme object.'].join('\\n'));\n }\n }\n const theme = React.useMemo(() => {\n const output = outerTheme === null ? localTheme : mergeOuterLocalTheme(outerTheme, localTheme);\n if (output != null) {\n output[nested] = outerTheme !== null;\n }\n return output;\n }, [localTheme, outerTheme]);\n return /*#__PURE__*/_jsx(ThemeContext.Provider, {\n value: theme,\n children: children\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: PropTypes.node,\n /**\n * A theme object. You can provide a function to extend the outer theme.\n */\n theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired\n} : void 0;\nif (process.env.NODE_ENV !== 'production') {\n process.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0;\n}\nexport default ThemeProvider;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { ThemeProvider as MuiThemeProvider, useTheme as usePrivateTheme } from '@mui/private-theming';\nimport exactProp from '@mui/utils/exactProp';\nimport { ThemeContext as StyledEngineThemeContext } from '@mui/styled-engine';\nimport useThemeWithoutDefault from '../useThemeWithoutDefault';\nimport RtlProvider from '../RtlProvider';\nimport DefaultPropsProvider from '../DefaultPropsProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst EMPTY_THEME = {};\nfunction useThemeScoping(themeId, upperTheme, localTheme, isPrivate = false) {\n return React.useMemo(() => {\n const resolvedTheme = themeId ? upperTheme[themeId] || upperTheme : upperTheme;\n if (typeof localTheme === 'function') {\n const mergedTheme = localTheme(resolvedTheme);\n const result = themeId ? _extends({}, upperTheme, {\n [themeId]: mergedTheme\n }) : mergedTheme;\n // must return a function for the private theme to NOT merge with the upper theme.\n // see the test case \"use provided theme from a callback\" in ThemeProvider.test.js\n if (isPrivate) {\n return () => result;\n }\n return result;\n }\n return themeId ? _extends({}, upperTheme, {\n [themeId]: localTheme\n }) : _extends({}, upperTheme, localTheme);\n }, [themeId, upperTheme, localTheme, isPrivate]);\n}\n\n/**\n * This component makes the `theme` available down the React tree.\n * It should preferably be used at **the root of your component tree**.\n *\n * // existing use case\n * // theme scoping\n */\nfunction ThemeProvider(props) {\n const {\n children,\n theme: localTheme,\n themeId\n } = props;\n const upperTheme = useThemeWithoutDefault(EMPTY_THEME);\n const upperPrivateTheme = usePrivateTheme() || EMPTY_THEME;\n if (process.env.NODE_ENV !== 'production') {\n if (upperTheme === null && typeof localTheme === 'function' || themeId && upperTheme && !upperTheme[themeId] && typeof localTheme === 'function') {\n console.error(['MUI: You are providing a theme function prop to the ThemeProvider component:', ' outerTheme} />', '', 'However, no outer theme is present.', 'Make sure a theme is already injected higher in the React tree ' + 'or provide a theme object.'].join('\\n'));\n }\n }\n const engineTheme = useThemeScoping(themeId, upperTheme, localTheme);\n const privateTheme = useThemeScoping(themeId, upperPrivateTheme, localTheme, true);\n const rtlValue = engineTheme.direction === 'rtl';\n return /*#__PURE__*/_jsx(MuiThemeProvider, {\n theme: privateTheme,\n children: /*#__PURE__*/_jsx(StyledEngineThemeContext.Provider, {\n value: engineTheme,\n children: /*#__PURE__*/_jsx(RtlProvider, {\n value: rtlValue,\n children: /*#__PURE__*/_jsx(DefaultPropsProvider, {\n value: engineTheme == null ? void 0 : engineTheme.components,\n children: children\n })\n })\n })\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Your component tree.\n */\n children: PropTypes.node,\n /**\n * A theme object. You can provide a function to extend the outer theme.\n */\n theme: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,\n /**\n * The design system's unique id for getting the corresponded theme when there are multiple design systems.\n */\n themeId: PropTypes.string\n} : void 0;\nif (process.env.NODE_ENV !== 'production') {\n process.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0;\n}\nexport default ThemeProvider;","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"theme\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { ThemeProvider as SystemThemeProvider } from '@mui/system';\nimport THEME_ID from './identifier';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default function ThemeProvider(_ref) {\n let {\n theme: themeInput\n } = _ref,\n props = _objectWithoutPropertiesLoose(_ref, _excluded);\n const scopedTheme = themeInput[THEME_ID];\n return /*#__PURE__*/_jsx(SystemThemeProvider, _extends({}, props, {\n themeId: scopedTheme ? THEME_ID : undefined,\n theme: scopedTheme || themeInput\n }));\n}\nprocess.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: PropTypes.node,\n /**\n * A theme object. You can provide a function to extend the outer theme.\n */\n theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired\n} : void 0;","export const palette = {\n primary: {\n main: '#5C67FF',\n },\n secondary: {\n main: '#F5B5FF',\n },\n success: {\n main: '#0AA65B',\n },\n warning: {\n main: '#FFCC00',\n },\n error: {\n main: '#E5452F',\n },\n info: {\n main: '#297EFF',\n },\n common: {\n black: '#000000',\n white: '#ffffff',\n },\n grey: {\n '200': '#eeeeee',\n '300': '#e0e0e0',\n '700': '#616161',\n '800': '#424242',\n },\n};\n\nexport const paletteDark = {\n background: {\n paper: '#212121',\n default: '#121212',\n },\n text: {\n primary: '#ffffff',\n secondary: '#bbbbbb',\n },\n};\n\nexport const paletteLight = {\n background: {\n paper: '#ffffff',\n default: '#ffffff',\n },\n text: {\n primary: '#000000',\n secondary: '#747474',\n },\n};\n","import type { WidgetTheme, WidgetThemeComponents } from '../types/widget.js';\n\ntype ComponentName = keyof WidgetThemeComponents;\n\nexport const getStyleOverrides = (\n componentName: ComponentName,\n styleOverrideProp: string,\n theme: WidgetTheme,\n ownerState?: any,\n) => {\n const component = theme.components?.[componentName];\n const property = (component?.styleOverrides as any)?.[styleOverrideProp];\n\n if (typeof property === 'function') {\n return property({ theme, ownerState });\n }\n return property;\n};\n","import { loadingButtonClasses } from '@mui/lab';\nimport type {} from '@mui/lab/themeAugmentation';\nimport type {\n CSSObject,\n PaletteMode,\n Shape,\n SimplePaletteColorOptions,\n} from '@mui/material';\nimport {\n alpha,\n createTheme as createMuiTheme,\n css,\n darken,\n dialogActionsClasses,\n getContrastRatio,\n keyframes,\n lighten,\n tabsClasses,\n touchRippleClasses,\n} from '@mui/material';\nimport type { WidgetTheme } from '../types/widget.js';\nimport { palette, paletteDark, paletteLight } from './palettes.js';\nimport type {} from './types.js';\nimport { getStyleOverrides } from './utils.js';\n\nconst shape: Shape = {\n borderRadius: 12,\n borderRadiusSecondary: 12,\n borderRadiusTertiary: 24,\n};\n\nconst enterKeyframe = keyframes`\n 0% {\n transform: scale(0);\n opacity: 0.05;\n }\n 100% {\n transform: scale(1);\n opacity: 0.1;\n }\n`;\n\nexport const createTheme = (\n mode: PaletteMode,\n widgetTheme: WidgetTheme = {},\n) => {\n const primaryMainColor =\n (widgetTheme.palette?.primary as SimplePaletteColorOptions)?.main ??\n palette.primary.main;\n const primaryLightColor = lighten(primaryMainColor, 0.84);\n const primaryDarkColor = darken(primaryMainColor, 0.2);\n const secondaryMainColor =\n (widgetTheme.palette?.secondary as SimplePaletteColorOptions)?.main ??\n palette.secondary.main;\n const contrastButtonColor =\n getContrastRatio(palette.common.white, primaryMainColor) >= 3\n ? palette.common.white\n : palette.common.black;\n const contrastTextButtonColor =\n getContrastRatio(palette.common.white, alpha(primaryMainColor, 0.08)) >= 3\n ? palette.common.white\n : palette.common.black;\n const borderRadiusSecondary =\n widgetTheme.shape?.borderRadiusSecondary ?? shape.borderRadiusSecondary;\n\n return createMuiTheme({\n container: widgetTheme.container,\n header: widgetTheme.header,\n navigation: {\n edge: true,\n ...widgetTheme.navigation,\n },\n typography: {\n fontFamily: 'Inter var, Inter, sans-serif',\n ...widgetTheme.typography,\n },\n palette: {\n mode,\n ...palette,\n ...(mode === 'light' ? paletteLight : paletteDark),\n ...widgetTheme.palette,\n primary: {\n main: primaryMainColor,\n light: primaryLightColor,\n dark: primaryDarkColor,\n },\n secondary: {\n main: secondaryMainColor,\n light: lighten(secondaryMainColor, 0.84),\n dark: darken(secondaryMainColor, 0.2),\n },\n },\n shape: {\n ...shape,\n ...widgetTheme.shape,\n },\n breakpoints: {\n values: {\n xs: 360,\n sm: 416,\n md: 900,\n lg: 1200,\n xl: 1536,\n },\n },\n components: {\n MuiScopedCssBaseline: {\n styleOverrides: {\n root: {\n fontFamily: 'Inter, sans-serif',\n ...widgetTheme.typography,\n '@supports (font-variation-settings: normal)': {\n fontFamily: 'Inter var, sans-serif',\n ...widgetTheme.typography,\n },\n },\n },\n },\n MuiAppBar: {\n styleOverrides: {\n root: ({ ownerState, theme }) => ({\n minHeight: 40,\n padding: 0,\n ...getStyleOverrides('MuiAppBar', 'root', widgetTheme, ownerState),\n }),\n },\n },\n MuiCard: {\n defaultProps: {\n variant: 'outlined',\n ...widgetTheme.components?.MuiCard?.defaultProps,\n },\n styleOverrides: {\n root: ({ ownerState, theme }) => {\n const root = widgetTheme.components?.MuiCard?.styleOverrides\n ?.root as CSSObject;\n const rootHover = root?.['&:hover'];\n return {\n backgroundColor: theme.palette.background.paper,\n borderRadius: theme.shape.borderRadius,\n overflow: 'hidden',\n position: 'relative',\n boxSizing: 'border-box',\n transition: theme.transitions.create(\n ['background-color', 'filter'],\n {\n duration: theme.transitions.duration.enteringScreen,\n easing: theme.transitions.easing.easeOut,\n },\n ),\n ...(!!ownerState.onClick && {\n '&:hover': {\n cursor: 'pointer',\n },\n }),\n ...(!!ownerState.onClick &&\n (ownerState.variant === 'outlined' ||\n ownerState.variant === 'filled') && {\n '&:hover': {\n cursor: 'pointer',\n backgroundColor:\n theme.palette.mode === 'light'\n ? darken(theme.palette.background.paper, 0.02)\n : lighten(theme.palette.background.paper, 0.02),\n },\n }),\n ...(!!ownerState.onClick &&\n ownerState.variant === 'elevation' && {\n '&:hover': {\n cursor: 'pointer',\n filter: `drop-shadow(0 1px 4px ${alpha(theme.palette.common.black, 0.08)})`,\n },\n }),\n ...(typeof root === 'object' && root),\n ...(!!ownerState.onClick &&\n !!rootHover && {\n '&:hover': {\n ...rootHover,\n },\n }),\n ...(!ownerState.onClick && {\n '&:hover': {},\n }),\n };\n },\n },\n variants: widgetTheme.components?.MuiCard?.variants ?? [\n {\n props: { variant: 'outlined' },\n style: ({ theme }) => ({\n borderWidth: 1,\n borderStyle: 'solid',\n borderColor:\n theme.palette.mode === 'light'\n ? theme.palette.grey[300]\n : theme.palette.grey[800],\n }),\n },\n {\n props: { variant: 'elevation' },\n style: ({ theme }) => ({\n border: 'none',\n boxShadow: 'none',\n filter: `drop-shadow(0 1px 4px ${alpha(theme.palette.common.black, 0.04)})`,\n }),\n },\n {\n props: { variant: 'filled' },\n style: {\n border: 'none',\n },\n },\n ],\n },\n MuiInputCard: {\n ...widgetTheme.components?.MuiInputCard,\n },\n MuiButtonBase: {\n styleOverrides: {\n // This `css()` function invokes keyframes. `styled-components` only supports keyframes\n // in string templates. Do not convert these styles in JS object as it will break.\n root: css`\n &\n .${touchRippleClasses.ripple}.${touchRippleClasses.rippleVisible} {\n opacity: 0.1;\n animation-name: ${enterKeyframe};\n }\n `,\n },\n },\n MuiButton: {\n defaultProps: {\n disableElevation: true,\n ...widgetTheme.components?.MuiButton?.defaultProps,\n },\n styleOverrides: {\n root: ({ theme, ownerState }) => ({\n borderRadius: borderRadiusSecondary,\n textTransform: 'none',\n fontSize: 16,\n fontWeight: 600,\n [`&.Mui-disabled, &.Mui-disabled:hover`]: {\n color: alpha(\n mode === 'light' ? palette.common.black : palette.common.white,\n 0.56,\n ),\n cursor: 'not-allowed',\n pointerEvents: 'auto',\n },\n [`&.${loadingButtonClasses.loading}.Mui-disabled`]: {\n backgroundColor: primaryMainColor,\n color: contrastButtonColor,\n cursor: 'auto',\n pointerEvents: 'auto',\n },\n [`.${loadingButtonClasses.loadingIndicator}`]: {\n color: contrastButtonColor,\n },\n [`&.${loadingButtonClasses.root}.${loadingButtonClasses.loading}`]:\n {\n color: 'transparent',\n },\n ...getStyleOverrides('MuiButton', 'root', widgetTheme, ownerState),\n }),\n text: ({ theme, ownerState }) => ({\n backgroundColor:\n mode === 'light'\n ? alpha(primaryMainColor, 0.08)\n : alpha(primaryMainColor, 0.42),\n '&:hover': {\n backgroundColor:\n mode === 'light'\n ? alpha(primaryMainColor, 0.12)\n : alpha(primaryMainColor, 0.56),\n },\n color:\n mode === 'light' ? primaryMainColor : contrastTextButtonColor,\n ...getStyleOverrides('MuiButton', 'text', widgetTheme, ownerState),\n }),\n contained: ({ theme, ownerState }) => ({\n '&:hover': {\n color: contrastButtonColor,\n },\n ...getStyleOverrides(\n 'MuiButton',\n 'contained',\n widgetTheme,\n ownerState,\n ),\n }),\n sizeMedium: ({ theme, ownerState }) => ({\n padding: '10px 14px',\n [`.${dialogActionsClasses.root} &`]: {\n padding: '6px 12px',\n },\n ...getStyleOverrides(\n 'MuiButton',\n 'sizeMedium',\n widgetTheme,\n ownerState,\n ),\n }),\n },\n },\n MuiIconButton: {\n ...widgetTheme.components?.MuiIconButton,\n styleOverrides: {\n ...widgetTheme.components?.MuiIconButton?.styleOverrides,\n root: ({ theme, ownerState }) => ({\n color: 'inherit',\n '&:hover': {\n color: 'inherit',\n },\n ...getStyleOverrides(\n 'MuiIconButton',\n 'root',\n widgetTheme,\n ownerState,\n ),\n }),\n },\n },\n MuiAvatar: {\n styleOverrides: {\n root: {\n height: 40,\n width: 40,\n },\n img: {\n objectFit: 'contain',\n },\n },\n ...widgetTheme.components?.MuiAvatar,\n },\n MuiListItemText: {\n styleOverrides: {\n primary: ({ theme }) => ({\n fontWeight: 600,\n fontSize: '1.125rem',\n lineHeight: '1.2778',\n color: theme.palette.text.primary,\n }),\n secondary: ({ theme }) => ({\n fontWeight: 500,\n fontSize: '0.75rem',\n color: theme.palette.text.secondary,\n }),\n },\n },\n MuiTooltip: {\n defaultProps: {\n enterDelay: 400,\n disableInteractive: true,\n arrow: true,\n placement: 'top',\n },\n styleOverrides: {\n tooltip: ({ theme }) => ({\n backgroundColor: 'rgb(0 0 0 / 64%)',\n backdropFilter: 'blur(3px)',\n fontSize: '0.75rem',\n padding: theme.spacing(1, 1.5),\n }),\n arrow: {\n color: 'rgb(0 0 0 / 64%)',\n },\n },\n },\n MuiMenu: {\n styleOverrides: {\n paper: ({ theme }) => ({\n backgroundColor: theme.palette.background.default,\n }),\n },\n },\n MuiTabs: {\n ...widgetTheme.components?.MuiTabs,\n styleOverrides: {\n ...widgetTheme.components?.MuiTabs?.styleOverrides,\n root: ({ theme, ownerState }) => {\n const rootStyleOverrides = getStyleOverrides(\n 'MuiTabs',\n 'root',\n widgetTheme,\n ownerState,\n );\n return {\n backgroundColor:\n theme.palette.mode === 'light'\n ? alpha(theme.palette.common.black, 0.04)\n : alpha(theme.palette.common.white, 0.08),\n borderRadius: theme.shape.borderRadius,\n ...rootStyleOverrides,\n [`.${tabsClasses.indicator}`]: {\n backgroundColor:\n theme.palette.mode === 'light'\n ? theme.palette.background.paper\n : alpha(theme.palette.common.black, 0.56),\n borderRadius:\n theme.shape.borderRadius > 0\n ? theme.shape.borderRadius - 4\n : theme.shape.borderRadius,\n boxShadow: `0px 2px 4px ${alpha(theme.palette.common.black, 0.04)}`,\n ...rootStyleOverrides?.[`.${tabsClasses.indicator}`],\n },\n };\n },\n },\n },\n },\n });\n};\n","import type { PaletteMode } from '@mui/material';\nimport {\n ThemeProvider as MuiThemeProvider,\n useMediaQuery,\n} from '@mui/material';\nimport { useEffect, useMemo, useState } from 'react';\nimport { useAppearance } from '../../stores/settings/useAppearance.js';\nimport { createTheme } from '../../themes/createTheme.js';\nimport { useWidgetConfig } from '../WidgetProvider/WidgetProvider.js';\n\nexport const ThemeProvider: React.FC> = ({\n children,\n}) => {\n const { appearance: colorSchemeMode, theme: themeConfig } = useWidgetConfig();\n const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');\n const [appearance, setAppearance] = useAppearance();\n const [mode, setMode] = useState(\n (colorSchemeMode ?? appearance === 'auto')\n ? prefersDarkMode\n ? 'dark'\n : 'light'\n : appearance,\n );\n\n useEffect(() => {\n if (appearance === 'auto') {\n setMode(prefersDarkMode ? 'dark' : 'light');\n } else {\n setMode(appearance);\n }\n }, [appearance, prefersDarkMode]);\n\n useEffect(() => {\n if (colorSchemeMode) {\n setAppearance(colorSchemeMode);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [colorSchemeMode]);\n\n const theme = useMemo(\n () => createTheme(mode, themeConfig),\n [mode, themeConfig],\n );\n return {children};\n};\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify | undefined\n }\n | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default 4_000\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default 4_000\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial>,\n >(\n fn: (\n client: Client,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType['config'] & ReturnType['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n cacheTime = parameters.pollingInterval ?? 4_000,\n ccipRead,\n key = 'base',\n name = 'Base Client',\n pollingInterval = 4_000,\n type = 'base',\n } = parameters\n\n const chain = parameters.chain\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema(): rpcSchema {\n return null as any\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../types.js'\n\nexport type ParseAccountErrorType = ErrorType\n\nexport function parseAccount(\n account: accountOrAddress,\n): accountOrAddress extends Address ? Account : accountOrAddress {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' } as any\n return account as any\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\ntype Resolved = [\n result: returnType[number],\n results: returnType,\n]\n\ntype PendingPromise = {\n resolve?: ((data: Resolved) => void) | undefined\n reject?: ((reason?: unknown) => void) | undefined\n}\n\ntype SchedulerItem = { args: unknown; pendingPromise: PendingPromise }\n\ntype BatchResultsCompareFn = (a: result, b: result) => number\n\ntype CreateBatchSchedulerArguments<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: parameters[]) => Promise\n id: number | string\n shouldSplitBatch?: ((args: parameters[]) => boolean) | undefined\n wait?: number | undefined\n sort?: BatchResultsCompareFn | undefined\n}\n\ntype CreateBatchSchedulerReturnType<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: parameters extends undefined\n ? (args?: parameters | undefined) => Promise>\n : (args: parameters) => Promise>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map()\n\n/** @internal */\nexport function createBatchScheduler<\n parameters,\n returnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n parameters,\n returnType\n>): CreateBatchSchedulerReturnType {\n const exec = async () => {\n const scheduler = getScheduler()\n flush()\n\n const args = scheduler.map(({ args }) => args)\n\n if (args.length === 0) return\n\n fn(args as parameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { pendingPromise } = scheduler[i]\n pendingPromise.resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { pendingPromise } = scheduler[i]\n pendingPromise.reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as parameters[]\n\n const getScheduler = () => schedulerCache.get(id) || []\n\n const setScheduler = (item: SchedulerItem) =>\n schedulerCache.set(id, [...getScheduler(), item])\n\n return {\n flush,\n async schedule(args: parameters) {\n const pendingPromise: PendingPromise = {}\n const promise = new Promise>((resolve, reject) => {\n pendingPromise.resolve = resolve\n pendingPromise.reject = reject\n })\n\n const split = shouldSplitBatch?.([...getBatchedArgs(), args])\n\n if (split) exec()\n\n const hasActiveScheduler = getScheduler().length > 0\n if (hasActiveScheduler) {\n setScheduler({ args, pendingPromise })\n return promise\n }\n\n setScheduler({ args, pendingPromise })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe(\n fn: () => Promise,\n { enabled = true, id }: WithDedupeOptions,\n): Promise {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport { keccak256 } from './hash/keccak256.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownRpcErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest Promise>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n const requestId = dedupe\n ? keccak256(stringToHex(`${uid}.${stringify(args)}`))\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n type HttpRpcClientOptions,\n getHttpRpcClient,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n type Transport,\n type TransportConfig,\n createTransport,\n} from './createTransport.js'\n\nexport type HttpTransportConfig = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n }\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig = {},\n): HttpTransport {\n const {\n batch,\n fetchOptions,\n key = 'http',\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit | undefined\n /** A callback to handle the request. */\n onRequest?: ((request: Request) => Promise | void) | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?: ((request: Request) => Promise | void) | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request(\n params: HttpRequestParameters,\n ): Promise>\n}\n\nexport function getHttpRpcClient(\n url: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n return {\n async request(params) {\n const {\n body,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n if (onRequest) await onRequest(request)\n const response = await fetch(url, init)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = ({\n chain,\n}: {\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record,\n>(\n {\n key,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig,\n value?: rpcAttributes | undefined,\n): ReturnType> {\n const uid = uid_()\n return {\n config: {\n key,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { retryCount, retryDelay, uid }),\n value,\n }\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain,\n>(chain: chain): Prettify, chain>> {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign, chain>\n}\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const mainnet = /*#__PURE__*/ defineChain({\n id: 1,\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://cloudflare-eth.com'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensRegistry: {\n address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',\n },\n ensUniversalResolver: {\n address: '0xce01f8eee7E479C928F8919abD53E553a36CeF67',\n blockCreated: 19_258_213,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n})\n","const reduxImpl = (reducer, initial) => (set, _get, api) => {\n api.dispatch = (action) => {\n set((state) => reducer(state, action), false, action);\n return action;\n };\n api.dispatchFromDevtools = true;\n return { dispatch: (...a) => api.dispatch(...a), ...initial };\n};\nconst redux = reduxImpl;\n\nconst trackedConnections = /* @__PURE__ */ new Map();\nconst getTrackedConnectionState = (name) => {\n const api = trackedConnections.get(name);\n if (!api)\n return {};\n return Object.fromEntries(\n Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])\n );\n};\nconst extractConnectionInformation = (store, extensionConnector, options) => {\n if (store === void 0) {\n return {\n type: \"untracked\",\n connection: extensionConnector.connect(options)\n };\n }\n const existingConnection = trackedConnections.get(options.name);\n if (existingConnection) {\n return { type: \"tracked\", store, ...existingConnection };\n }\n const newConnection = {\n connection: extensionConnector.connect(options),\n stores: {}\n };\n trackedConnections.set(options.name, newConnection);\n return { type: \"tracked\", store, ...newConnection };\n};\nconst devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {\n const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;\n let extensionConnector;\n try {\n extensionConnector = (enabled != null ? enabled : (import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") && window.__REDUX_DEVTOOLS_EXTENSION__;\n } catch (e) {\n }\n if (!extensionConnector) {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && enabled) {\n console.warn(\n \"[zustand devtools middleware] Please install/enable Redux devtools extension\"\n );\n }\n return fn(set, get, api);\n }\n const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);\n let isRecording = true;\n api.setState = (state, replace, nameOrAction) => {\n const r = set(state, replace);\n if (!isRecording)\n return r;\n const action = nameOrAction === void 0 ? { type: anonymousActionType || \"anonymous\" } : typeof nameOrAction === \"string\" ? { type: nameOrAction } : nameOrAction;\n if (store === void 0) {\n connection == null ? void 0 : connection.send(action, get());\n return r;\n }\n connection == null ? void 0 : connection.send(\n {\n ...action,\n type: `${store}/${action.type}`\n },\n {\n ...getTrackedConnectionState(options.name),\n [store]: api.getState()\n }\n );\n return r;\n };\n const setStateFromDevtools = (...a) => {\n const originalIsRecording = isRecording;\n isRecording = false;\n set(...a);\n isRecording = originalIsRecording;\n };\n const initialState = fn(api.setState, get, api);\n if (connectionInformation.type === \"untracked\") {\n connection == null ? void 0 : connection.init(initialState);\n } else {\n connectionInformation.stores[connectionInformation.store] = api;\n connection == null ? void 0 : connection.init(\n Object.fromEntries(\n Object.entries(connectionInformation.stores).map(([key, store2]) => [\n key,\n key === connectionInformation.store ? initialState : store2.getState()\n ])\n )\n );\n }\n if (api.dispatchFromDevtools && typeof api.dispatch === \"function\") {\n let didWarnAboutReservedActionType = false;\n const originalDispatch = api.dispatch;\n api.dispatch = (...a) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && a[0].type === \"__setState\" && !didWarnAboutReservedActionType) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved to set state from the devtools. Avoid using it.'\n );\n didWarnAboutReservedActionType = true;\n }\n originalDispatch(...a);\n };\n }\n connection.subscribe((message) => {\n var _a;\n switch (message.type) {\n case \"ACTION\":\n if (typeof message.payload !== \"string\") {\n console.error(\n \"[zustand devtools middleware] Unsupported action format\"\n );\n return;\n }\n return parseJsonThen(\n message.payload,\n (action) => {\n if (action.type === \"__setState\") {\n if (store === void 0) {\n setStateFromDevtools(action.state);\n return;\n }\n if (Object.keys(action.state).length !== 1) {\n console.error(\n `\n [zustand devtools middleware] Unsupported __setState action format. \n When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n `\n );\n }\n const stateFromDevtools = action.state[store];\n if (stateFromDevtools === void 0 || stateFromDevtools === null) {\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {\n setStateFromDevtools(stateFromDevtools);\n }\n return;\n }\n if (!api.dispatchFromDevtools)\n return;\n if (typeof api.dispatch !== \"function\")\n return;\n api.dispatch(action);\n }\n );\n case \"DISPATCH\":\n switch (message.payload.type) {\n case \"RESET\":\n setStateFromDevtools(initialState);\n if (store === void 0) {\n return connection == null ? void 0 : connection.init(api.getState());\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"COMMIT\":\n if (store === void 0) {\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"ROLLBACK\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n setStateFromDevtools(state[store]);\n connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n });\n case \"JUMP_TO_STATE\":\n case \"JUMP_TO_ACTION\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {\n setStateFromDevtools(state[store]);\n }\n });\n case \"IMPORT_STATE\": {\n const { nextLiftedState } = message.payload;\n const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;\n if (!lastComputedState)\n return;\n if (store === void 0) {\n setStateFromDevtools(lastComputedState);\n } else {\n setStateFromDevtools(lastComputedState[store]);\n }\n connection == null ? void 0 : connection.send(\n null,\n // FIXME no-any\n nextLiftedState\n );\n return;\n }\n case \"PAUSE_RECORDING\":\n return isRecording = !isRecording;\n }\n return;\n }\n });\n return initialState;\n};\nconst devtools = devtoolsImpl;\nconst parseJsonThen = (stringified, f) => {\n let parsed;\n try {\n parsed = JSON.parse(stringified);\n } catch (e) {\n console.error(\n \"[zustand devtools middleware] Could not parse the received json\",\n e\n );\n }\n if (parsed !== void 0)\n f(parsed);\n};\n\nconst subscribeWithSelectorImpl = (fn) => (set, get, api) => {\n const origSubscribe = api.subscribe;\n api.subscribe = (selector, optListener, options) => {\n let listener = selector;\n if (optListener) {\n const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;\n let currentSlice = selector(api.getState());\n listener = (state) => {\n const nextSlice = selector(state);\n if (!equalityFn(currentSlice, nextSlice)) {\n const previousSlice = currentSlice;\n optListener(currentSlice = nextSlice, previousSlice);\n }\n };\n if (options == null ? void 0 : options.fireImmediately) {\n optListener(currentSlice, currentSlice);\n }\n }\n return origSubscribe(listener);\n };\n const initialState = fn(set, get, api);\n return initialState;\n};\nconst subscribeWithSelector = subscribeWithSelectorImpl;\n\nconst combine = (initialState, create) => (...a) => Object.assign({}, initialState, create(...a));\n\nfunction createJSONStorage(getStorage, options) {\n let storage;\n try {\n storage = getStorage();\n } catch (e) {\n return;\n }\n const persistStorage = {\n getItem: (name) => {\n var _a;\n const parse = (str2) => {\n if (str2 === null) {\n return null;\n }\n return JSON.parse(str2, options == null ? void 0 : options.reviver);\n };\n const str = (_a = storage.getItem(name)) != null ? _a : null;\n if (str instanceof Promise) {\n return str.then(parse);\n }\n return parse(str);\n },\n setItem: (name, newValue) => storage.setItem(\n name,\n JSON.stringify(newValue, options == null ? void 0 : options.replacer)\n ),\n removeItem: (name) => storage.removeItem(name)\n };\n return persistStorage;\n}\nconst toThenable = (fn) => (input) => {\n try {\n const result = fn(input);\n if (result instanceof Promise) {\n return result;\n }\n return {\n then(onFulfilled) {\n return toThenable(onFulfilled)(result);\n },\n catch(_onRejected) {\n return this;\n }\n };\n } catch (e) {\n return {\n then(_onFulfilled) {\n return this;\n },\n catch(onRejected) {\n return toThenable(onRejected)(e);\n }\n };\n }\n};\nconst oldImpl = (config, baseOptions) => (set, get, api) => {\n let options = {\n getStorage: () => localStorage,\n serialize: JSON.stringify,\n deserialize: JSON.parse,\n partialize: (state) => state,\n version: 0,\n merge: (persistedState, currentState) => ({\n ...currentState,\n ...persistedState\n }),\n ...baseOptions\n };\n let hasHydrated = false;\n const hydrationListeners = /* @__PURE__ */ new Set();\n const finishHydrationListeners = /* @__PURE__ */ new Set();\n let storage;\n try {\n storage = options.getStorage();\n } catch (e) {\n }\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`\n );\n set(...args);\n },\n get,\n api\n );\n }\n const thenableSerialize = toThenable(options.serialize);\n const setItem = () => {\n const state = options.partialize({ ...get() });\n let errorInSync;\n const thenable = thenableSerialize({ state, version: options.version }).then(\n (serializedValue) => storage.setItem(options.name, serializedValue)\n ).catch((e) => {\n errorInSync = e;\n });\n if (errorInSync) {\n throw errorInSync;\n }\n return thenable;\n };\n const savedSetState = api.setState;\n api.setState = (state, replace) => {\n savedSetState(state, replace);\n void setItem();\n };\n const configResult = config(\n (...args) => {\n set(...args);\n void setItem();\n },\n get,\n api\n );\n let stateFromStorage;\n const hydrate = () => {\n var _a;\n if (!storage)\n return;\n hasHydrated = false;\n hydrationListeners.forEach((cb) => cb(get()));\n const postRehydrationCallback = ((_a = options.onRehydrateStorage) == null ? void 0 : _a.call(options, get())) || void 0;\n return toThenable(storage.getItem.bind(storage))(options.name).then((storageValue) => {\n if (storageValue) {\n return options.deserialize(storageValue);\n }\n }).then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (typeof deserializedStorageValue.version === \"number\" && deserializedStorageValue.version !== options.version) {\n if (options.migrate) {\n return options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version\n );\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`\n );\n } else {\n return deserializedStorageValue.state;\n }\n }\n }).then((migratedState) => {\n var _a2;\n stateFromStorage = options.merge(\n migratedState,\n (_a2 = get()) != null ? _a2 : configResult\n );\n set(stateFromStorage, true);\n return setItem();\n }).then(() => {\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);\n hasHydrated = true;\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage));\n }).catch((e) => {\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);\n });\n };\n api.persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions\n };\n if (newOptions.getStorage) {\n storage = newOptions.getStorage();\n }\n },\n clearStorage: () => {\n storage == null ? void 0 : storage.removeItem(options.name);\n },\n getOptions: () => options,\n rehydrate: () => hydrate(),\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb);\n return () => {\n hydrationListeners.delete(cb);\n };\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb);\n return () => {\n finishHydrationListeners.delete(cb);\n };\n }\n };\n hydrate();\n return stateFromStorage || configResult;\n};\nconst newImpl = (config, baseOptions) => (set, get, api) => {\n let options = {\n storage: createJSONStorage(() => localStorage),\n partialize: (state) => state,\n version: 0,\n merge: (persistedState, currentState) => ({\n ...currentState,\n ...persistedState\n }),\n ...baseOptions\n };\n let hasHydrated = false;\n const hydrationListeners = /* @__PURE__ */ new Set();\n const finishHydrationListeners = /* @__PURE__ */ new Set();\n let storage = options.storage;\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`\n );\n set(...args);\n },\n get,\n api\n );\n }\n const setItem = () => {\n const state = options.partialize({ ...get() });\n return storage.setItem(options.name, {\n state,\n version: options.version\n });\n };\n const savedSetState = api.setState;\n api.setState = (state, replace) => {\n savedSetState(state, replace);\n void setItem();\n };\n const configResult = config(\n (...args) => {\n set(...args);\n void setItem();\n },\n get,\n api\n );\n let stateFromStorage;\n const hydrate = () => {\n var _a, _b;\n if (!storage)\n return;\n hasHydrated = false;\n hydrationListeners.forEach((cb) => {\n var _a2;\n return cb((_a2 = get()) != null ? _a2 : configResult);\n });\n const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;\n return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (typeof deserializedStorageValue.version === \"number\" && deserializedStorageValue.version !== options.version) {\n if (options.migrate) {\n return options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version\n );\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`\n );\n } else {\n return deserializedStorageValue.state;\n }\n }\n }).then((migratedState) => {\n var _a2;\n stateFromStorage = options.merge(\n migratedState,\n (_a2 = get()) != null ? _a2 : configResult\n );\n set(stateFromStorage, true);\n return setItem();\n }).then(() => {\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);\n stateFromStorage = get();\n hasHydrated = true;\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage));\n }).catch((e) => {\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);\n });\n };\n api.persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions\n };\n if (newOptions.storage) {\n storage = newOptions.storage;\n }\n },\n clearStorage: () => {\n storage == null ? void 0 : storage.removeItem(options.name);\n },\n getOptions: () => options,\n rehydrate: () => hydrate(),\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb);\n return () => {\n hydrationListeners.delete(cb);\n };\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb);\n return () => {\n finishHydrationListeners.delete(cb);\n };\n }\n };\n if (!options.skipHydration) {\n hydrate();\n }\n return stateFromStorage || configResult;\n};\nconst persistImpl = (config, baseOptions) => {\n if (\"getStorage\" in baseOptions || \"serialize\" in baseOptions || \"deserialize\" in baseOptions) {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\n \"[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead.\"\n );\n }\n return oldImpl(config, baseOptions);\n }\n return newImpl(config, baseOptions);\n};\nconst persist = persistImpl;\n\nexport { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector };\n","const createStoreImpl = (createState) => {\n let state;\n const listeners = /* @__PURE__ */ new Set();\n const setState = (partial, replace) => {\n const nextState = typeof partial === \"function\" ? partial(state) : partial;\n if (!Object.is(nextState, state)) {\n const previousState = state;\n state = (replace != null ? replace : typeof nextState !== \"object\") ? nextState : Object.assign({}, state, nextState);\n listeners.forEach((listener) => listener(state, previousState));\n }\n };\n const getState = () => state;\n const subscribe = (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n const destroy = () => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\n \"[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected.\"\n );\n }\n listeners.clear();\n };\n const api = { setState, getState, subscribe, destroy };\n state = createState(setState, getState, api);\n return api;\n};\nconst createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;\nvar vanilla = (createState) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\n \"[DEPRECATED] Default export is deprecated. Instead use import { createStore } from 'zustand/vanilla'.\"\n );\n }\n return createStore(createState);\n};\n\nexport { createStore, vanilla as default };\n","import {\n type AddEthereumChainParameter,\n type Address,\n type EIP1193Provider,\n type ProviderConnectInfo,\n type ProviderRpcError,\n ResourceUnavailableRpcError,\n type RpcError,\n SwitchChainError,\n UserRejectedRequestError,\n getAddress,\n numberToHex,\n withRetry,\n withTimeout,\n} from 'viem'\n\nimport type { Connector } from '../createConfig.js'\nimport { ChainNotConfiguredError } from '../errors/config.js'\nimport { ProviderNotFoundError } from '../errors/connector.js'\nimport type { Compute } from '../types/utils.js'\nimport { createConnector } from './createConnector.js'\n\nexport type InjectedParameters = {\n /**\n * Some injected providers do not support programmatic disconnect.\n * This flag simulates the disconnect behavior by keeping track of connection status in storage.\n * @default true\n */\n shimDisconnect?: boolean | undefined\n /**\n * [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target\n */\n target?: TargetId | Target | (() => Target | undefined) | undefined\n unstable_shimAsyncInject?: boolean | number | undefined\n}\n\n// Regex of wallets/providers that can accurately simulate contract calls & display contract revert reasons.\nconst supportsSimulationIdRegex = /(rabby|trustwallet)/\n\nconst targetMap = {\n coinbaseWallet: {\n id: 'coinbaseWallet',\n name: 'Coinbase Wallet',\n provider(window) {\n if (window?.coinbaseWalletExtension) return window.coinbaseWalletExtension\n return findProvider(window, 'isCoinbaseWallet')\n },\n },\n metaMask: {\n id: 'metaMask',\n name: 'MetaMask',\n provider(window) {\n return findProvider(window, (provider) => {\n if (!provider.isMetaMask) return false\n // Brave tries to make itself look like MetaMask\n // Could also try RPC `web3_clientVersion` if following is unreliable\n if (provider.isBraveWallet && !provider._events && !provider._state)\n return false\n // Other wallets that try to look like MetaMask\n const flags: WalletProviderFlags[] = [\n 'isApexWallet',\n 'isAvalanche',\n 'isBitKeep',\n 'isBlockWallet',\n 'isKuCoinWallet',\n 'isMathWallet',\n 'isOkxWallet',\n 'isOKExWallet',\n 'isOneInchIOSWallet',\n 'isOneInchAndroidWallet',\n 'isOpera',\n 'isPortal',\n 'isRabby',\n 'isTokenPocket',\n 'isTokenary',\n 'isZerion',\n ]\n for (const flag of flags) if (provider[flag]) return false\n return true\n })\n },\n },\n phantom: {\n id: 'phantom',\n name: 'Phantom',\n provider(window) {\n if (window?.phantom?.ethereum) return window.phantom?.ethereum\n return findProvider(window, 'isPhantom')\n },\n },\n} as const satisfies TargetMap\n\ninjected.type = 'injected' as const\nexport function injected(parameters: InjectedParameters = {}) {\n const { shimDisconnect = true, unstable_shimAsyncInject } = parameters\n\n function getTarget(): Compute {\n const target = parameters.target\n if (typeof target === 'function') {\n const result = target()\n if (result) return result\n }\n\n if (typeof target === 'object') return target\n\n if (typeof target === 'string')\n return {\n ...(targetMap[target as keyof typeof targetMap] ?? {\n id: target,\n name: `${target[0]!.toUpperCase()}${target.slice(1)}`,\n provider: `is${target[0]!.toUpperCase()}${target.slice(1)}`,\n }),\n }\n\n return {\n id: 'injected',\n name: 'Injected',\n provider(window) {\n return window?.ethereum\n },\n }\n }\n\n type Provider = WalletProvider | undefined\n type Properties = {\n onConnect(connectInfo: ProviderConnectInfo): void\n }\n type StorageItem = {\n [_ in 'injected.connected' | `${string}.disconnected`]: true\n }\n\n let accountsChanged: Connector['onAccountsChanged'] | undefined\n let chainChanged: Connector['onChainChanged'] | undefined\n let connect: Connector['onConnect'] | undefined\n let disconnect: Connector['onDisconnect'] | undefined\n\n return createConnector((config) => ({\n get icon() {\n return getTarget().icon\n },\n get id() {\n return getTarget().id\n },\n get name() {\n return getTarget().name\n },\n get supportsSimulation() {\n return supportsSimulationIdRegex.test(this.id.toLowerCase())\n },\n type: injected.type,\n async setup() {\n const provider = await this.getProvider()\n // Only start listening for events if `target` is set, otherwise `injected()` will also receive events\n if (provider?.on && parameters.target) {\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect)\n }\n\n // We shouldn't need to listen for `'accountsChanged'` here since the `'connect'` event should suffice (and wallet shouldn't be connected yet).\n // Some wallets, like MetaMask, do not implement the `'connect'` event and overload `'accountsChanged'` instead.\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged)\n }\n }\n },\n async connect({ chainId, isReconnecting } = {}) {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n\n let accounts: readonly Address[] = []\n if (isReconnecting) accounts = await this.getAccounts().catch(() => [])\n else if (shimDisconnect) {\n // Attempt to show another prompt for selecting account if `shimDisconnect` flag is enabled\n try {\n const permissions = await provider.request({\n method: 'wallet_requestPermissions',\n params: [{ eth_accounts: {} }],\n })\n accounts = (permissions[0]?.caveats?.[0]?.value as string[])?.map(\n (x) => getAddress(x),\n )\n // `'wallet_requestPermissions'` can return a different order of accounts than `'eth_accounts'`\n // switch to `'eth_accounts'` ordering if more than one account is connected\n // https://github.com/wevm/wagmi/issues/4140\n if (accounts.length > 0) {\n const sortedAccounts = await this.getAccounts()\n accounts = sortedAccounts\n }\n } catch (err) {\n const error = err as RpcError\n // Not all injected providers support `wallet_requestPermissions` (e.g. MetaMask iOS).\n // Only bubble up error if user rejects request\n if (error.code === UserRejectedRequestError.code)\n throw new UserRejectedRequestError(error)\n // Or prompt is already open\n if (error.code === ResourceUnavailableRpcError.code) throw error\n }\n }\n\n try {\n if (!accounts?.length && !isReconnecting) {\n const requestedAccounts = await provider.request({\n method: 'eth_requestAccounts',\n })\n accounts = requestedAccounts.map((x) => getAddress(x))\n }\n\n // Manage EIP-1193 event listeners\n // https://eips.ethereum.org/EIPS/eip-1193#events\n if (connect) {\n provider.removeListener('connect', connect)\n connect = undefined\n }\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect)\n }\n\n // Switch to chain if provided\n let currentChainId = await this.getChainId()\n if (chainId && currentChainId !== chainId) {\n const chain = await this.switchChain!({ chainId }).catch((error) => {\n if (error.code === UserRejectedRequestError.code) throw error\n return { id: currentChainId }\n })\n currentChainId = chain?.id ?? currentChainId\n }\n\n // Remove disconnected shim if it exists\n if (shimDisconnect)\n await config.storage?.removeItem(`${this.id}.disconnected`)\n\n // Add connected shim if no target exists\n if (!parameters.target)\n await config.storage?.setItem('injected.connected', true)\n\n return { accounts, chainId: currentChainId }\n } catch (err) {\n const error = err as RpcError\n if (error.code === UserRejectedRequestError.code)\n throw new UserRejectedRequestError(error)\n if (error.code === ResourceUnavailableRpcError.code)\n throw new ResourceUnavailableRpcError(error)\n throw error\n }\n },\n async disconnect() {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n\n // Manage EIP-1193 event listeners\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect)\n }\n\n // Experimental support for MetaMask disconnect\n // https://github.com/MetaMask/metamask-improvement-proposals/blob/main/MIPs/mip-2.md\n try {\n // Adding timeout as not all wallets support this method and can hang\n // https://github.com/wevm/wagmi/issues/4064\n await withTimeout(\n () =>\n // TODO: Remove explicit type for viem@3\n provider.request<{\n Method: 'wallet_revokePermissions'\n Parameters: [permissions: { eth_accounts: Record }]\n ReturnType: null\n }>({\n // `'wallet_revokePermissions'` added in `viem@2.10.3`\n method: 'wallet_revokePermissions',\n params: [{ eth_accounts: {} }],\n }),\n { timeout: 100 },\n )\n } catch {}\n\n // Add shim signalling connector is disconnected\n if (shimDisconnect) {\n await config.storage?.setItem(`${this.id}.disconnected`, true)\n }\n\n if (!parameters.target)\n await config.storage?.removeItem('injected.connected')\n },\n async getAccounts() {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n const accounts = await provider.request({ method: 'eth_accounts' })\n return accounts.map((x) => getAddress(x))\n },\n async getChainId() {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n const hexChainId = await provider.request({ method: 'eth_chainId' })\n return Number(hexChainId)\n },\n async getProvider() {\n if (typeof window === 'undefined') return undefined\n\n let provider: Provider\n const target = getTarget()\n if (typeof target.provider === 'function')\n provider = target.provider(window as Window | undefined)\n else if (typeof target.provider === 'string')\n provider = findProvider(window, target.provider)\n else provider = target.provider\n\n // Some wallets do not conform to EIP-1193 (e.g. Trust Wallet)\n // https://github.com/wevm/wagmi/issues/3526#issuecomment-1912683002\n if (provider && !provider.removeListener) {\n // Try using `off` handler if it exists, otherwise noop\n if ('off' in provider && typeof provider.off === 'function')\n provider.removeListener =\n provider.off as typeof provider.removeListener\n else provider.removeListener = () => {}\n }\n\n return provider\n },\n async isAuthorized() {\n try {\n const isDisconnected =\n shimDisconnect &&\n // If shim exists in storage, connector is disconnected\n (await config.storage?.getItem(`${this.id}.disconnected`))\n if (isDisconnected) return false\n\n // Don't allow injected connector to connect if no target is set and it hasn't already connected\n // (e.g. flag in storage is not set). This prevents a targetless injected connector from connecting\n // automatically whenever there is a targeted connector configured.\n if (!parameters.target) {\n const connected = await config.storage?.getItem('injected.connected')\n if (!connected) return false\n }\n\n const provider = await this.getProvider()\n if (!provider) {\n if (\n unstable_shimAsyncInject !== undefined &&\n unstable_shimAsyncInject !== false\n ) {\n // If no provider is found, check for async injection\n // https://github.com/wevm/references/issues/167\n // https://github.com/MetaMask/detect-provider\n const handleEthereum = async () => {\n if (typeof window !== 'undefined')\n window.removeEventListener(\n 'ethereum#initialized',\n handleEthereum,\n )\n const provider = await this.getProvider()\n return !!provider\n }\n const timeout =\n typeof unstable_shimAsyncInject === 'number'\n ? unstable_shimAsyncInject\n : 1_000\n const res = await Promise.race([\n ...(typeof window !== 'undefined'\n ? [\n new Promise((resolve) =>\n window.addEventListener(\n 'ethereum#initialized',\n () => resolve(handleEthereum()),\n { once: true },\n ),\n ),\n ]\n : []),\n new Promise((resolve) =>\n setTimeout(() => resolve(handleEthereum()), timeout),\n ),\n ])\n if (res) return true\n }\n\n throw new ProviderNotFoundError()\n }\n\n // Use retry strategy as some injected wallets (e.g. MetaMask) fail to\n // immediately resolve JSON-RPC requests on page load.\n const accounts = await withRetry(() => this.getAccounts())\n return !!accounts.length\n } catch {\n return false\n }\n },\n async switchChain({ addEthereumChainParameter, chainId }) {\n const provider = await this.getProvider()\n if (!provider) throw new ProviderNotFoundError()\n\n const chain = config.chains.find((x) => x.id === chainId)\n if (!chain) throw new SwitchChainError(new ChainNotConfiguredError())\n\n try {\n await Promise.all([\n provider\n .request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: numberToHex(chainId) }],\n })\n // During `'wallet_switchEthereumChain'`, MetaMask makes a `'net_version'` RPC call to the target chain.\n // If this request fails, MetaMask does not emit the `'chainChanged'` event, but will still switch the chain.\n // To counter this behavior, we request and emit the current chain ID to confirm the chain switch either via\n // this callback or an externally emitted `'chainChanged'` event.\n // https://github.com/MetaMask/metamask-extension/issues/24247\n .then(async () => {\n const currentChainId = await this.getChainId()\n if (currentChainId === chainId)\n config.emitter.emit('change', { chainId })\n }),\n new Promise((resolve) => {\n const listener = ((data) => {\n if ('chainId' in data && data.chainId === chainId) {\n config.emitter.off('change', listener)\n resolve()\n }\n }) satisfies Parameters[1]\n config.emitter.on('change', listener)\n }),\n ])\n return chain\n } catch (err) {\n const error = err as RpcError\n\n // Indicates chain is not added to provider\n if (\n error.code === 4902 ||\n // Unwrapping for MetaMask Mobile\n // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719\n (error as ProviderRpcError<{ originalError?: { code: number } }>)\n ?.data?.originalError?.code === 4902\n ) {\n try {\n const { default: blockExplorer, ...blockExplorers } =\n chain.blockExplorers ?? {}\n let blockExplorerUrls: string[] | undefined\n if (addEthereumChainParameter?.blockExplorerUrls)\n blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls\n else if (blockExplorer)\n blockExplorerUrls = [\n blockExplorer.url,\n ...Object.values(blockExplorers).map((x) => x.url),\n ]\n\n let rpcUrls: readonly string[]\n if (addEthereumChainParameter?.rpcUrls?.length)\n rpcUrls = addEthereumChainParameter.rpcUrls\n else rpcUrls = [chain.rpcUrls.default?.http[0] ?? '']\n\n const addEthereumChain = {\n blockExplorerUrls,\n chainId: numberToHex(chainId),\n chainName: addEthereumChainParameter?.chainName ?? chain.name,\n iconUrls: addEthereumChainParameter?.iconUrls,\n nativeCurrency:\n addEthereumChainParameter?.nativeCurrency ??\n chain.nativeCurrency,\n rpcUrls,\n } satisfies AddEthereumChainParameter\n\n await provider.request({\n method: 'wallet_addEthereumChain',\n params: [addEthereumChain],\n })\n\n const currentChainId = await this.getChainId()\n if (currentChainId !== chainId)\n throw new UserRejectedRequestError(\n new Error('User rejected switch after adding network.'),\n )\n\n return chain\n } catch (error) {\n throw new UserRejectedRequestError(error as Error)\n }\n }\n\n if (error.code === UserRejectedRequestError.code)\n throw new UserRejectedRequestError(error)\n throw new SwitchChainError(error)\n }\n },\n async onAccountsChanged(accounts) {\n // Disconnect if there are no accounts\n if (accounts.length === 0) this.onDisconnect()\n // Connect if emitter is listening for connect event (e.g. is disconnected and connects through wallet interface)\n else if (config.emitter.listenerCount('connect')) {\n const chainId = (await this.getChainId()).toString()\n this.onConnect({ chainId })\n // Remove disconnected shim if it exists\n if (shimDisconnect)\n await config.storage?.removeItem(`${this.id}.disconnected`)\n }\n // Regular change event\n else\n config.emitter.emit('change', {\n accounts: accounts.map((x) => getAddress(x)),\n })\n },\n onChainChanged(chain) {\n const chainId = Number(chain)\n config.emitter.emit('change', { chainId })\n },\n async onConnect(connectInfo) {\n const accounts = await this.getAccounts()\n if (accounts.length === 0) return\n\n const chainId = Number(connectInfo.chainId)\n config.emitter.emit('connect', { accounts, chainId })\n\n // Manage EIP-1193 event listeners\n const provider = await this.getProvider()\n if (provider) {\n if (connect) {\n provider.removeListener('connect', connect)\n connect = undefined\n }\n if (!accountsChanged) {\n accountsChanged = this.onAccountsChanged.bind(this)\n provider.on('accountsChanged', accountsChanged)\n }\n if (!chainChanged) {\n chainChanged = this.onChainChanged.bind(this)\n provider.on('chainChanged', chainChanged)\n }\n if (!disconnect) {\n disconnect = this.onDisconnect.bind(this)\n provider.on('disconnect', disconnect)\n }\n }\n },\n async onDisconnect(error) {\n const provider = await this.getProvider()\n\n // If MetaMask emits a `code: 1013` error, wait for reconnection before disconnecting\n // https://github.com/MetaMask/providers/pull/120\n if (error && (error as RpcError<1013>).code === 1013) {\n if (provider && !!(await this.getAccounts()).length) return\n }\n\n // No need to remove `${this.id}.disconnected` from storage because `onDisconnect` is typically\n // only called when the wallet is disconnected through the wallet's interface, meaning the wallet\n // actually disconnected and we don't need to simulate it.\n config.emitter.emit('disconnect')\n\n // Manage EIP-1193 event listeners\n if (provider) {\n if (chainChanged) {\n provider.removeListener('chainChanged', chainChanged)\n chainChanged = undefined\n }\n if (disconnect) {\n provider.removeListener('disconnect', disconnect)\n disconnect = undefined\n }\n if (!connect) {\n connect = this.onConnect.bind(this)\n provider.on('connect', connect)\n }\n }\n },\n }))\n}\n\ntype Target = {\n icon?: string | undefined\n id: string\n name: string\n provider:\n | WalletProviderFlags\n | WalletProvider\n | ((window?: Window | undefined) => WalletProvider | undefined)\n}\n\n/** @deprecated */\ntype TargetId = Compute extends `is${infer name}`\n ? name extends `${infer char}${infer rest}`\n ? `${Lowercase}${rest}`\n : never\n : never\n\ntype TargetMap = { [_ in TargetId]?: Target | undefined }\n\n/** @deprecated */\ntype WalletProviderFlags =\n | 'isApexWallet'\n | 'isAvalanche'\n | 'isBackpack'\n | 'isBifrost'\n | 'isBitKeep'\n | 'isBitski'\n | 'isBlockWallet'\n | 'isBraveWallet'\n | 'isCoinbaseWallet'\n | 'isDawn'\n | 'isEnkrypt'\n | 'isExodus'\n | 'isFrame'\n | 'isFrontier'\n | 'isGamestop'\n | 'isHyperPay'\n | 'isImToken'\n | 'isKuCoinWallet'\n | 'isMathWallet'\n | 'isMetaMask'\n | 'isOkxWallet'\n | 'isOKExWallet'\n | 'isOneInchAndroidWallet'\n | 'isOneInchIOSWallet'\n | 'isOpera'\n | 'isPhantom'\n | 'isPortal'\n | 'isRabby'\n | 'isRainbow'\n | 'isStatus'\n | 'isTally'\n | 'isTokenPocket'\n | 'isTokenary'\n | 'isTrust'\n | 'isTrustWallet'\n | 'isXDEFI'\n | 'isZerion'\n\ntype WalletProvider = Compute<\n EIP1193Provider & {\n [key in WalletProviderFlags]?: true | undefined\n } & {\n providers?: WalletProvider[] | undefined\n /** Only exists in MetaMask as of 2022/04/03 */\n _events?: { connect?: (() => void) | undefined } | undefined\n /** Only exists in MetaMask as of 2022/04/03 */\n _state?:\n | {\n accounts?: string[]\n initialized?: boolean\n isConnected?: boolean\n isPermanentlyDisconnected?: boolean\n isUnlocked?: boolean\n }\n | undefined\n }\n>\n\ntype Window = {\n coinbaseWalletExtension?: WalletProvider | undefined\n ethereum?: WalletProvider | undefined\n phantom?: { ethereum: WalletProvider } | undefined\n}\n\nfunction findProvider(\n window: globalThis.Window | Window | undefined,\n select?: WalletProviderFlags | ((provider: WalletProvider) => boolean),\n) {\n function isProvider(provider: WalletProvider) {\n if (typeof select === 'function') return select(provider)\n if (typeof select === 'string') return provider[select]\n return true\n }\n\n const ethereum = (window as Window).ethereum\n if (ethereum?.providers)\n return ethereum.providers.find((provider) => isProvider(provider))\n if (ethereum && isProvider(ethereum)) return ethereum\n return undefined\n}\n","import { EventEmitter } from 'eventemitter3'\n\ntype EventMap = Record\ntype EventKey = string & keyof eventMap\ntype EventFn = (\n ...parameters: parameters\n) => void\nexport type EventData<\n eventMap extends EventMap,\n eventName extends keyof eventMap,\n> = (eventMap[eventName] extends [never] ? unknown : eventMap[eventName]) & {\n uid: string\n}\n\nexport class Emitter {\n _emitter = new EventEmitter()\n\n constructor(public uid: string) {}\n\n on>(\n eventName: key,\n fn: EventFn<\n eventMap[key] extends [never]\n ? [{ uid: string }]\n : [data: eventMap[key] & { uid: string }]\n >,\n ) {\n this._emitter.on(eventName, fn as EventFn)\n }\n\n once>(\n eventName: key,\n fn: EventFn<\n eventMap[key] extends [never]\n ? [{ uid: string }]\n : [data: eventMap[key] & { uid: string }]\n >,\n ) {\n this._emitter.once(eventName, fn as EventFn)\n }\n\n off>(\n eventName: key,\n fn: EventFn<\n eventMap[key] extends [never]\n ? [{ uid: string }]\n : [data: eventMap[key] & { uid: string }]\n >,\n ) {\n this._emitter.off(eventName, fn as EventFn)\n }\n\n emit>(\n eventName: key,\n ...params: eventMap[key] extends [never] ? [] : [data: eventMap[key]]\n ) {\n const data = params[0]\n this._emitter.emit(eventName, { uid: this.uid, ...data })\n }\n\n listenerCount>(eventName: key) {\n return this._emitter.listenerCount(eventName)\n }\n}\n\nexport function createEmitter(uid: string) {\n return new Emitter(uid)\n}\n","type Reviver = (key: string, value: any) => any\n\nexport function deserialize(value: string, reviver?: Reviver): type {\n return JSON.parse(value, (key, value_) => {\n let value = value_\n if (value?.__type === 'bigint') value = BigInt(value.value)\n if (value?.__type === 'Map') value = new Map(value.value)\n return reviver?.(key, value) ?? value\n })\n}\n","/**\n * Get the reference key for the circular value\n *\n * @param keys the keys to build the reference key from\n * @param cutoff the maximum number of keys to include\n * @returns the reference key\n */\nfunction getReferenceKey(keys: string[], cutoff: number) {\n return keys.slice(0, cutoff).join('.') || '.'\n}\n\n/**\n * Faster `Array.prototype.indexOf` implementation build for slicing / splicing\n *\n * @param array the array to match the value in\n * @param value the value to match\n * @returns the matching index, or -1\n */\nfunction getCutoff(array: any[], value: any) {\n const { length } = array\n\n for (let index = 0; index < length; ++index) {\n if (array[index] === value) {\n return index + 1\n }\n }\n\n return 0\n}\n\ntype StandardReplacer = (key: string, value: any) => any\ntype CircularReplacer = (key: string, value: any, referenceKey: string) => any\n\n/**\n * Create a replacer method that handles circular values\n *\n * @param [replacer] a custom replacer to use for non-circular values\n * @param [circularReplacer] a custom replacer to use for circular methods\n * @returns the value to stringify\n */\nfunction createReplacer(\n replacer?: StandardReplacer | null | undefined,\n circularReplacer?: CircularReplacer | null | undefined,\n): StandardReplacer {\n const hasReplacer = typeof replacer === 'function'\n const hasCircularReplacer = typeof circularReplacer === 'function'\n\n const cache: any[] = []\n const keys: string[] = []\n\n return function replace(this: any, key: string, value: any) {\n if (typeof value === 'object') {\n if (cache.length) {\n const thisCutoff = getCutoff(cache, this)\n\n if (thisCutoff === 0) {\n cache[cache.length] = this\n } else {\n cache.splice(thisCutoff)\n keys.splice(thisCutoff)\n }\n\n keys[keys.length] = key\n\n const valueCutoff = getCutoff(cache, value)\n\n if (valueCutoff !== 0) {\n return hasCircularReplacer\n ? circularReplacer.call(\n this,\n key,\n value,\n getReferenceKey(keys, valueCutoff),\n )\n : `[ref=${getReferenceKey(keys, valueCutoff)}]`\n }\n } else {\n cache[0] = value\n keys[0] = key\n }\n }\n\n return hasReplacer ? replacer.call(this, key, value) : value\n }\n}\n\n/**\n * Stringifier that handles circular values\n *\n * Forked from https://github.com/planttheidea/fast-stringify\n *\n * @param value to stringify\n * @param [replacer] a custom replacer function for handling standard values\n * @param [indent] the number of spaces to indent the output by\n * @param [circularReplacer] a custom replacer function for handling circular values\n * @returns the stringified output\n */\nexport function serialize(\n value: any,\n replacer?: StandardReplacer | null | undefined,\n indent?: number | null | undefined,\n circularReplacer?: CircularReplacer | null | undefined,\n) {\n return JSON.stringify(\n value,\n createReplacer((key, value_) => {\n let value = value_\n if (typeof value === 'bigint')\n value = { __type: 'bigint', value: value_.toString() }\n if (value instanceof Map)\n value = { __type: 'Map', value: Array.from(value_.entries()) }\n return replacer?.(key, value) ?? value\n }, circularReplacer),\n indent ?? undefined,\n )\n}\n","import type { PartializedState } from './createConfig.js'\nimport type { Compute } from './types/utils.js'\nimport { deserialize as deserialize_ } from './utils/deserialize.js'\nimport { serialize as serialize_ } from './utils/serialize.js'\n\n// key-values for loose autocomplete and typing\nexport type StorageItemMap = {\n recentConnectorId: string\n state: PartializedState\n}\n\nexport type Storage<\n itemMap extends Record = Record,\n ///\n storageItemMap extends StorageItemMap = StorageItemMap & itemMap,\n> = {\n key: string\n getItem<\n key extends keyof storageItemMap,\n value extends storageItemMap[key],\n defaultValue extends value | null | undefined,\n >(\n key: key,\n defaultValue?: defaultValue | undefined,\n ):\n | (defaultValue extends null ? value | null : value)\n | Promise\n setItem<\n key extends keyof storageItemMap,\n value extends storageItemMap[key] | null,\n >(key: key, value: value): void | Promise\n removeItem(key: keyof storageItemMap): void | Promise\n}\n\nexport type BaseStorage = {\n getItem(\n key: string,\n ): string | null | undefined | Promise\n setItem(key: string, value: string): void | Promise\n removeItem(key: string): void | Promise\n}\n\nexport type CreateStorageParameters = {\n deserialize?: ((value: string) => type | unknown) | undefined\n key?: string | undefined\n serialize?: ((value: type | any) => string) | undefined\n storage?: Compute | undefined\n}\n\nexport function createStorage<\n itemMap extends Record = Record,\n storageItemMap extends StorageItemMap = StorageItemMap & itemMap,\n>(parameters: CreateStorageParameters): Compute> {\n const {\n deserialize = deserialize_,\n key: prefix = 'wagmi',\n serialize = serialize_,\n storage = noopStorage,\n } = parameters\n\n function unwrap(value: type): type | Promise {\n if (value instanceof Promise) return value.then((x) => x).catch(() => null)\n return value\n }\n\n return {\n ...storage,\n key: prefix,\n async getItem(key, defaultValue) {\n const value = storage.getItem(`${prefix}.${key as string}`)\n const unwrapped = await unwrap(value)\n if (unwrapped) return deserialize(unwrapped) ?? null\n return (defaultValue ?? null) as any\n },\n async setItem(key, value) {\n const storageKey = `${prefix}.${key as string}`\n if (value === null) await unwrap(storage.removeItem(storageKey))\n else await unwrap(storage.setItem(storageKey, serialize(value)))\n },\n async removeItem(key) {\n await unwrap(storage.removeItem(`${prefix}.${key as string}`))\n },\n }\n}\n\nexport const noopStorage = {\n getItem: () => null,\n setItem: () => {},\n removeItem: () => {},\n} satisfies BaseStorage\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import {\n type EIP6963ProviderDetail,\n type Store as MipdStore,\n createStore as createMipd,\n} from 'mipd'\nimport {\n type Address,\n type Chain,\n type Client,\n type EIP1193RequestFn,\n createClient,\n type ClientConfig as viem_ClientConfig,\n type Transport as viem_Transport,\n} from 'viem'\nimport { persist, subscribeWithSelector } from 'zustand/middleware'\nimport { type Mutate, type StoreApi, createStore } from 'zustand/vanilla'\n\nimport type {\n ConnectorEventMap,\n CreateConnectorFn,\n} from './connectors/createConnector.js'\nimport { injected } from './connectors/injected.js'\nimport { type Emitter, type EventData, createEmitter } from './createEmitter.js'\nimport { type Storage, createStorage, noopStorage } from './createStorage.js'\nimport { ChainNotConfiguredError } from './errors/config.js'\nimport type {\n Compute,\n ExactPartial,\n LooseOmit,\n OneOf,\n RemoveUndefined,\n} from './types/utils.js'\nimport { uid } from './utils/uid.js'\nimport { version } from './version.js'\n\nexport type CreateConfigParameters<\n chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]],\n transports extends Record = Record<\n chains[number]['id'],\n Transport\n >,\n> = Compute<\n {\n chains: chains\n connectors?: CreateConnectorFn[] | undefined\n multiInjectedProviderDiscovery?: boolean | undefined\n storage?: Storage | null | undefined\n ssr?: boolean | undefined\n syncConnectedChain?: boolean | undefined\n } & OneOf<\n | ({ transports: transports } & {\n [key in keyof ClientConfig]?:\n | ClientConfig[key]\n | { [_ in chains[number]['id']]?: ClientConfig[key] | undefined }\n | undefined\n })\n | {\n client(parameters: { chain: chains[number] }): Client<\n transports[chains[number]['id']],\n chains[number]\n >\n }\n >\n>\n\nexport function createConfig<\n const chains extends readonly [Chain, ...Chain[]],\n transports extends Record,\n>(\n parameters: CreateConfigParameters,\n): Config {\n const {\n multiInjectedProviderDiscovery = true,\n storage = createStorage({\n storage:\n typeof window !== 'undefined' && window.localStorage\n ? window.localStorage\n : noopStorage,\n }),\n syncConnectedChain = true,\n ssr = false,\n ...rest\n } = parameters\n\n /////////////////////////////////////////////////////////////////////////////////////////////////\n // Set up connectors, clients, etc.\n /////////////////////////////////////////////////////////////////////////////////////////////////\n\n const mipd =\n typeof window !== 'undefined' && multiInjectedProviderDiscovery\n ? createMipd()\n : undefined\n\n const chains = createStore(() => rest.chains)\n const connectors = createStore(() =>\n [\n ...(rest.connectors ?? []),\n ...(!ssr\n ? mipd?.getProviders().map(providerDetailToConnector) ?? []\n : []),\n ].map(setup),\n )\n function setup(connectorFn: CreateConnectorFn): Connector {\n // Set up emitter with uid and add to connector so they are \"linked\" together.\n const emitter = createEmitter(uid())\n const connector = {\n ...connectorFn({\n emitter,\n chains: chains.getState(),\n storage,\n transports: rest.transports,\n }),\n emitter,\n uid: emitter.uid,\n }\n\n // Start listening for `connect` events on connector setup\n // This allows connectors to \"connect\" themselves without user interaction (e.g. MetaMask's \"Manually connect to current site\")\n emitter.on('connect', connect)\n connector.setup?.()\n\n return connector\n }\n function providerDetailToConnector(providerDetail: EIP6963ProviderDetail) {\n const { info } = providerDetail\n const provider = providerDetail.provider as any\n return injected({ target: { ...info, id: info.rdns, provider } })\n }\n\n const clients = new Map>()\n function getClient(\n config: { chainId?: chainId | chains[number]['id'] | undefined } = {},\n ): Client> {\n const chainId = config.chainId ?? store.getState().chainId\n const chain = chains.getState().find((x) => x.id === chainId)\n\n // chainId specified and not configured\n if (config.chainId && !chain) throw new ChainNotConfiguredError()\n\n // If the target chain is not configured, use the client of the current chain.\n type Return = Client>\n {\n const client = clients.get(store.getState().chainId)\n if (client && !chain) return client as Return\n if (!chain) throw new ChainNotConfiguredError()\n }\n\n // If a memoized client exists for a chain id, use that.\n {\n const client = clients.get(chainId)\n if (client) return client as Return\n }\n\n let client: Client\n if (rest.client) client = rest.client({ chain })\n else {\n const chainId = chain.id as chains[number]['id']\n const chainIds = chains.getState().map((x) => x.id)\n // Grab all properties off `rest` and resolve for use in `createClient`\n const properties: Partial = {}\n const entries = Object.entries(rest) as [keyof typeof rest, any][]\n\n for (const [key, value] of entries) {\n if (\n key === 'chains' ||\n key === 'client' ||\n key === 'connectors' ||\n key === 'transports'\n )\n continue\n\n if (typeof value === 'object') {\n // check if value is chainId-specific since some values can be objects\n // e.g. { batch: { multicall: { batchSize: 1024 } } }\n if (chainId in value) properties[key] = value[chainId]\n else {\n // check if value is chainId-specific, but does not have value for current chainId\n const hasChainSpecificValue = chainIds.some((x) => x in value)\n if (hasChainSpecificValue) continue\n properties[key] = value\n }\n } else properties[key] = value\n }\n\n client = createClient({\n ...properties,\n chain,\n batch: properties.batch ?? { multicall: true },\n transport: (parameters) =>\n rest.transports[chainId]({ ...parameters, connectors }),\n })\n }\n\n clients.set(chainId, client)\n return client as Return\n }\n\n /////////////////////////////////////////////////////////////////////////////////////////////////\n // Create store\n /////////////////////////////////////////////////////////////////////////////////////////////////\n\n function getInitialState(): State {\n return {\n chainId: chains.getState()[0].id,\n connections: new Map(),\n current: null,\n status: 'disconnected',\n }\n }\n\n let currentVersion: number\n const prefix = '0.0.0-canary-'\n if (version.startsWith(prefix))\n currentVersion = Number.parseInt(version.replace(prefix, ''))\n // use package major version to version store\n else currentVersion = Number.parseInt(version.split('.')[0] ?? '0')\n\n const store = createStore(\n subscribeWithSelector(\n // only use persist middleware if storage exists\n storage\n ? persist(getInitialState, {\n migrate(persistedState, version) {\n if (version === currentVersion) return persistedState as State\n\n const initialState = getInitialState()\n const chainId = validatePersistedChainId(\n persistedState,\n initialState.chainId,\n )\n return { ...initialState, chainId }\n },\n name: 'store',\n partialize(state) {\n // Only persist \"critical\" store properties to preserve storage size.\n return {\n connections: {\n __type: 'Map',\n value: Array.from(state.connections.entries()).map(\n ([key, connection]) => {\n const { id, name, type, uid } = connection.connector\n const connector = { id, name, type, uid }\n return [key, { ...connection, connector }]\n },\n ),\n } as unknown as PartializedState['connections'],\n chainId: state.chainId,\n current: state.current,\n } satisfies PartializedState\n },\n merge(persistedState, currentState) {\n // `status` should not be persisted as it messes with reconnection\n if (\n typeof persistedState === 'object' &&\n persistedState &&\n 'status' in persistedState\n )\n delete persistedState.status\n // Make sure persisted `chainId` is valid\n const chainId = validatePersistedChainId(\n persistedState,\n currentState.chainId,\n )\n return {\n ...currentState,\n ...(persistedState as object),\n chainId,\n }\n },\n skipHydration: ssr,\n storage: storage as Storage>,\n version: currentVersion,\n })\n : getInitialState,\n ),\n )\n\n function validatePersistedChainId(\n persistedState: unknown,\n defaultChainId: number,\n ) {\n return persistedState &&\n typeof persistedState === 'object' &&\n 'chainId' in persistedState &&\n typeof persistedState.chainId === 'number' &&\n chains.getState().some((x) => x.id === persistedState.chainId)\n ? persistedState.chainId\n : defaultChainId\n }\n\n /////////////////////////////////////////////////////////////////////////////////////////////////\n // Subscribe to changes\n /////////////////////////////////////////////////////////////////////////////////////////////////\n\n // Update default chain when connector chain changes\n if (syncConnectedChain)\n store.subscribe(\n ({ connections, current }) =>\n current ? connections.get(current)?.chainId : undefined,\n (chainId) => {\n // If chain is not configured, then don't switch over to it.\n const isChainConfigured = chains\n .getState()\n .some((x) => x.id === chainId)\n if (!isChainConfigured) return\n\n return store.setState((x) => ({\n ...x,\n chainId: chainId ?? x.chainId,\n }))\n },\n )\n\n // EIP-6963 subscribe for new wallet providers\n mipd?.subscribe((providerDetails) => {\n const currentConnectorIds = new Map()\n for (const connector of connectors.getState()) {\n currentConnectorIds.set(connector.id, true)\n }\n\n const newConnectors: Connector[] = []\n for (const providerDetail of providerDetails) {\n const connector = setup(providerDetailToConnector(providerDetail))\n if (currentConnectorIds.has(connector.id)) continue\n newConnectors.push(connector)\n }\n\n if (storage && !store.persist.hasHydrated()) return\n connectors.setState((x) => [...x, ...newConnectors], true)\n })\n\n /////////////////////////////////////////////////////////////////////////////////////////////////\n // Emitter listeners\n /////////////////////////////////////////////////////////////////////////////////////////////////\n\n function change(data: EventData) {\n store.setState((x) => {\n const connection = x.connections.get(data.uid)\n if (!connection) return x\n return {\n ...x,\n connections: new Map(x.connections).set(data.uid, {\n accounts:\n (data.accounts as readonly [Address, ...Address[]]) ??\n connection.accounts,\n chainId: data.chainId ?? connection.chainId,\n connector: connection.connector,\n }),\n }\n })\n }\n function connect(data: EventData) {\n // Disable handling if reconnecting/connecting\n if (\n store.getState().status === 'connecting' ||\n store.getState().status === 'reconnecting'\n )\n return\n\n store.setState((x) => {\n const connector = connectors.getState().find((x) => x.uid === data.uid)\n if (!connector) return x\n\n if (connector.emitter.listenerCount('connect'))\n connector.emitter.off('connect', change)\n if (!connector.emitter.listenerCount('change'))\n connector.emitter.on('change', change)\n if (!connector.emitter.listenerCount('disconnect'))\n connector.emitter.on('disconnect', disconnect)\n\n return {\n ...x,\n connections: new Map(x.connections).set(data.uid, {\n accounts: data.accounts as readonly [Address, ...Address[]],\n chainId: data.chainId,\n connector: connector,\n }),\n current: data.uid,\n status: 'connected',\n }\n })\n }\n function disconnect(data: EventData) {\n store.setState((x) => {\n const connection = x.connections.get(data.uid)\n if (connection) {\n const connector = connection.connector\n if (connector.emitter.listenerCount('change'))\n connection.connector.emitter.off('change', change)\n if (connector.emitter.listenerCount('disconnect'))\n connection.connector.emitter.off('disconnect', disconnect)\n if (!connector.emitter.listenerCount('connect'))\n connection.connector.emitter.on('connect', connect)\n }\n\n x.connections.delete(data.uid)\n\n if (x.connections.size === 0)\n return {\n ...x,\n connections: new Map(),\n current: null,\n status: 'disconnected',\n }\n\n const nextConnection = x.connections.values().next().value as Connection\n return {\n ...x,\n connections: new Map(x.connections),\n current: nextConnection.connector.uid,\n }\n })\n }\n\n return {\n get chains() {\n return chains.getState() as chains\n },\n get connectors() {\n return connectors.getState()\n },\n storage,\n\n getClient,\n get state() {\n return store.getState() as unknown as State\n },\n setState(value) {\n let newState: State\n if (typeof value === 'function') newState = value(store.getState() as any)\n else newState = value\n\n // Reset state if it got set to something not matching the base state\n const initialState = getInitialState()\n if (typeof newState !== 'object') newState = initialState\n const isCorrupt = Object.keys(initialState).some((x) => !(x in newState))\n if (isCorrupt) newState = initialState\n\n store.setState(newState, true)\n },\n subscribe(selector, listener, options) {\n return store.subscribe(\n selector as unknown as (state: State) => any,\n listener,\n options\n ? ({\n ...options,\n fireImmediately: options.emitImmediately,\n // Workaround cast since Zustand does not support `'exactOptionalPropertyTypes'`\n } as RemoveUndefined)\n : undefined,\n )\n },\n\n _internal: {\n mipd,\n store,\n ssr: Boolean(ssr),\n syncConnectedChain,\n transports: rest.transports as transports,\n chains: {\n setState(value) {\n const nextChains = (\n typeof value === 'function' ? value(chains.getState()) : value\n ) as chains\n if (nextChains.length === 0) return\n return chains.setState(nextChains, true)\n },\n subscribe(listener) {\n return chains.subscribe(listener)\n },\n },\n connectors: {\n providerDetailToConnector,\n setup,\n setState(value) {\n return connectors.setState(\n typeof value === 'function' ? value(connectors.getState()) : value,\n true,\n )\n },\n subscribe(listener) {\n return connectors.subscribe(listener)\n },\n },\n events: { change, connect, disconnect },\n },\n }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\nexport type Config<\n chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]],\n transports extends Record = Record<\n chains[number]['id'],\n Transport\n >,\n> = {\n readonly chains: chains\n readonly connectors: readonly Connector[]\n readonly storage: Storage | null\n\n readonly state: State\n setState(\n value: State | ((state: State) => State),\n ): void\n subscribe(\n selector: (state: State) => state,\n listener: (state: state, previousState: state) => void,\n options?:\n | {\n emitImmediately?: boolean | undefined\n equalityFn?: ((a: state, b: state) => boolean) | undefined\n }\n | undefined,\n ): () => void\n\n getClient(parameters?: {\n chainId?: chainId | chains[number]['id'] | undefined\n }): Client>\n\n /**\n * Not part of versioned API, proceed with caution.\n * @internal\n */\n _internal: Internal\n}\n\ntype Internal<\n chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]],\n transports extends Record = Record<\n chains[number]['id'],\n Transport\n >,\n> = {\n readonly mipd: MipdStore | undefined\n readonly store: Mutate, [['zustand/persist', any]]>\n readonly ssr: boolean\n readonly syncConnectedChain: boolean\n readonly transports: transports\n\n chains: {\n setState(\n value:\n | readonly [Chain, ...Chain[]]\n | ((\n state: readonly [Chain, ...Chain[]],\n ) => readonly [Chain, ...Chain[]]),\n ): void\n subscribe(\n listener: (\n state: readonly [Chain, ...Chain[]],\n prevState: readonly [Chain, ...Chain[]],\n ) => void,\n ): () => void\n }\n connectors: {\n providerDetailToConnector(\n providerDetail: EIP6963ProviderDetail,\n ): CreateConnectorFn\n setup(connectorFn: CreateConnectorFn): Connector\n setState(value: Connector[] | ((state: Connector[]) => Connector[])): void\n subscribe(\n listener: (state: Connector[], prevState: Connector[]) => void,\n ): () => void\n }\n events: {\n change(data: EventData): void\n connect(data: EventData): void\n disconnect(data: EventData): void\n }\n}\n\nexport type State<\n chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]],\n> = {\n chainId: chains[number]['id']\n connections: Map\n current: string | null\n status: 'connected' | 'connecting' | 'disconnected' | 'reconnecting'\n}\n\nexport type PartializedState = Compute<\n ExactPartial>\n>\n\nexport type Connection = {\n accounts: readonly [Address, ...Address[]]\n chainId: number\n connector: Connector\n}\n\nexport type Connector = ReturnType & {\n emitter: Emitter\n uid: string\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = (\n params: Parameters<\n viem_Transport\n >[0] & {\n connectors?: StoreApi | undefined\n },\n) => ReturnType>\n\ntype ClientConfig = LooseOmit<\n viem_ClientConfig,\n 'account' | 'chain' | 'key' | 'name' | 'transport' | 'type'\n>\n",null,"import type { Address } from 'viem'\n\nimport type { CreateConnectorFn } from '../connectors/createConnector.js'\nimport type { Config, Connection, Connector } from '../createConfig.js'\nimport type { ErrorType } from '../errors/base.js'\nimport type { Compute } from '../types/utils.js'\n\nexport type ReconnectParameters = {\n /** Connectors to attempt reconnect with */\n connectors?: readonly (CreateConnectorFn | Connector)[] | undefined\n}\n\nexport type ReconnectReturnType = Compute[]\n\nexport type ReconnectErrorType = ErrorType\n\nlet isReconnecting = false\n\n/** https://wagmi.sh/core/api/actions/reconnect */\nexport async function reconnect(\n config: Config,\n parameters: ReconnectParameters = {},\n): Promise {\n // If already reconnecting, do nothing\n if (isReconnecting) return []\n isReconnecting = true\n\n config.setState((x) => ({\n ...x,\n status: x.current ? 'reconnecting' : 'connecting',\n }))\n\n const connectors: Connector[] = []\n if (parameters.connectors?.length) {\n for (const connector_ of parameters.connectors) {\n let connector: Connector\n // \"Register\" connector if not already created\n if (typeof connector_ === 'function')\n connector = config._internal.connectors.setup(connector_)\n else connector = connector_\n connectors.push(connector)\n }\n } else connectors.push(...config.connectors)\n\n // Try recently-used connectors first\n let recentConnectorId: string | null | undefined\n try {\n recentConnectorId = await config.storage?.getItem('recentConnectorId')\n } catch {}\n const scores: Record = {}\n for (const [, connection] of config.state.connections) {\n scores[connection.connector.id] = 1\n }\n if (recentConnectorId) scores[recentConnectorId] = 0\n const sorted =\n Object.keys(scores).length > 0\n ? // .toSorted()\n [...connectors].sort(\n (a, b) => (scores[a.id] ?? 10) - (scores[b.id] ?? 10),\n )\n : connectors\n\n // Iterate through each connector and try to connect\n let connected = false\n const connections: Connection[] = []\n const providers: unknown[] = []\n for (const connector of sorted) {\n const provider = await connector.getProvider().catch(() => undefined)\n if (!provider) continue\n\n // If we already have an instance of this connector's provider,\n // then we have already checked it (ie. injected connectors can\n // share the same `window.ethereum` instance, so we don't want to\n // connect to it again).\n if (providers.some((x) => x === provider)) continue\n\n const isAuthorized = await connector.isAuthorized()\n if (!isAuthorized) continue\n\n const data = await connector\n .connect({ isReconnecting: true })\n .catch(() => null)\n if (!data) continue\n\n connector.emitter.off('connect', config._internal.events.connect)\n connector.emitter.on('change', config._internal.events.change)\n connector.emitter.on('disconnect', config._internal.events.disconnect)\n\n config.setState((x) => {\n const connections = new Map(connected ? x.connections : new Map()).set(\n connector.uid,\n { accounts: data.accounts, chainId: data.chainId, connector },\n )\n return {\n ...x,\n current: connected ? x.current : connector.uid,\n connections,\n }\n })\n connections.push({\n accounts: data.accounts as readonly [Address, ...Address[]],\n chainId: data.chainId,\n connector,\n })\n providers.push(provider)\n connected = true\n }\n\n // Prevent overwriting connected status from race condition\n if (\n config.state.status === 'reconnecting' ||\n config.state.status === 'connecting'\n ) {\n // If connecting didn't succeed, set to disconnected\n if (!connected)\n config.setState((x) => ({\n ...x,\n connections: new Map(),\n current: null,\n status: 'disconnected',\n }))\n else config.setState((x) => ({ ...x, status: 'connected' }))\n }\n\n isReconnecting = false\n return connections\n}\n",null,null,"import type { DefaultWagmiConfigResult } from '@lifi/wallet-management';\nimport {\n createDefaultWagmiConfig,\n useSyncWagmiConfig,\n} from '@lifi/wallet-management';\nimport { useRef, type FC, type PropsWithChildren } from 'react';\nimport { WagmiProvider } from 'wagmi';\nimport { defaultCoinbaseConfig } from '../../config/coinbase.js';\nimport { defaultMetaMaskConfig } from '../../config/metaMask.js';\nimport { defaultWalletConnectConfig } from '../../config/walletConnect.js';\nimport { useAvailableChains } from '../../hooks/useAvailableChains.js';\nimport { useWidgetConfig } from '../WidgetProvider/WidgetProvider.js';\n\nexport const EVMBaseProvider: FC = ({ children }) => {\n const { walletConfig } = useWidgetConfig();\n const { chains } = useAvailableChains();\n const wagmi = useRef();\n\n if (!wagmi.current) {\n wagmi.current = createDefaultWagmiConfig({\n coinbase: walletConfig?.coinbase ?? defaultCoinbaseConfig,\n metaMask: walletConfig?.metaMask ?? defaultMetaMaskConfig,\n walletConnect: walletConfig?.walletConnect ?? defaultWalletConnectConfig,\n wagmiConfig: {\n ssr: true,\n },\n lazy: true,\n });\n }\n\n useSyncWagmiConfig(wagmi.current.config, wagmi.current.connectors, chains);\n\n return (\n \n {children}\n \n );\n};\n",null,null,"import { ChainType } from '@lifi/sdk';\nimport { useContext, type FC, type PropsWithChildren } from 'react';\nimport { WagmiContext } from 'wagmi';\nimport { isItemAllowed } from '../../utils/item.js';\nimport { useWidgetConfig } from '../WidgetProvider/WidgetProvider.js';\nimport { EVMBaseProvider } from './EVMBaseProvider.js';\nimport { EVMExternalContext } from './EVMExternalContext.js';\n\nexport function useInWagmiContext(): boolean {\n const { chains } = useWidgetConfig();\n const context = useContext(WagmiContext);\n\n return Boolean(context) && isItemAllowed(ChainType.EVM, chains?.types);\n}\n\nexport const EVMProvider: FC = ({ children }) => {\n const inWagmiContext = useInWagmiContext();\n\n return inWagmiContext ? (\n \n {children}\n \n ) : (\n {children}\n );\n};\n","import { BaseError } from './base.js'\n\nexport type AccountNotFoundErrorType = AccountNotFoundError & {\n name: 'AccountNotFoundError'\n}\nexport class AccountNotFoundError extends BaseError {\n constructor({ docsPath }: { docsPath?: string | undefined } = {}) {\n super(\n [\n 'Could not find an Account to execute with this Action.',\n 'Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client.',\n ].join('\\n'),\n {\n docsPath,\n docsSlug: 'account',\n name: 'AccountNotFoundError',\n },\n )\n }\n}\n\nexport type AccountTypeNotSupportedErrorType = AccountTypeNotSupportedError & {\n name: 'AccountTypeNotSupportedError'\n}\nexport class AccountTypeNotSupportedError extends BaseError {\n constructor({\n docsPath,\n metaMessages,\n type,\n }: {\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n type: string\n }) {\n super(`Account type \"${type}\" is not supported.`, {\n docsPath,\n metaMessages,\n name: 'AccountTypeNotSupportedError',\n })\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise {\n return publicKeyToAddress(await recoverPublicKey({ hash: hash, signature }))\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n | ChecksumAddressErrorType\n | Keccak256ErrorType\n | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n return checksumAddress(`0x${address}`) as Address\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray = T | readonly RecursiveArray[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n | CreateCursorErrorType\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\nexport function toRlp(\n bytes: RecursiveArray | RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n const encodable = getEncodable(bytes)\n const cursor = createCursor(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType\n return cursor.bytes as ToRlpReturnType\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp(\n bytes: RecursiveArray,\n to: to | To | undefined = 'bytes',\n): ToRlpReturnType {\n return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp(\n hex: RecursiveArray,\n to: to | To | undefined = 'hex',\n): ToRlpReturnType {\n return toRlp(hex, to)\n}\n\nfunction getEncodable(\n bytes: RecursiveArray | RecursiveArray,\n): Encodable {\n if (Array.isArray(bytes))\n return getEncodableList(bytes.map((x) => getEncodable(x)))\n return getEncodableBytes(bytes as any)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n const sizeOfBodyLength = getSizeOfLength(bodyLength)\n const length = (() => {\n if (bodyLength <= 55) return 1 + bodyLength\n return 1 + sizeOfBodyLength + bodyLength\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bodyLength <= 55) {\n cursor.pushByte(0xc0 + bodyLength)\n } else {\n cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n else cursor.pushUint32(bodyLength)\n }\n for (const { encode } of list) {\n encode(cursor)\n }\n },\n }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n const sizeOfBytesLength = getSizeOfLength(bytes.length)\n const length = (() => {\n if (bytes.length === 1 && bytes[0] < 0x80) return 1\n if (bytes.length <= 55) return 1 + bytes.length\n return 1 + sizeOfBytesLength + bytes.length\n })()\n\n return {\n length,\n encode(cursor: Cursor) {\n if (bytes.length === 1 && bytes[0] < 0x80) {\n cursor.pushBytes(bytes)\n } else if (bytes.length <= 55) {\n cursor.pushByte(0x80 + bytes.length)\n cursor.pushBytes(bytes)\n } else {\n cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n else cursor.pushUint32(bytes.length)\n cursor.pushBytes(bytes)\n }\n },\n }\n}\n\nfunction getSizeOfLength(length: number) {\n if (length < 2 ** 8) return 1\n if (length < 2 ** 16) return 2\n if (length < 2 ** 24) return 3\n if (length < 2 ** 32) return 4\n throw new BaseError('Length is too large.')\n}\n","import type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../../types/misc.js'\nimport {\n type ConcatHexErrorType,\n concatHex,\n} from '../../../utils/data/concat.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../../utils/encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../../../utils/encoding/toRlp.js'\nimport {\n type Keccak256ErrorType,\n keccak256,\n} from '../../../utils/hash/keccak256.js'\nimport type { Authorization } from '../types/authorization.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters = Authorization & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n}\n\nexport type HashAuthorizationReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization(\n parameters: HashAuthorizationParameters,\n): HashAuthorizationReturnType {\n const { chainId, contractAddress, nonce, to } = parameters\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n numberToHex(chainId),\n contractAddress,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType\n return hash as HashAuthorizationReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../../types/misc.js'\nimport type { OneOf } from '../../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../../utils/signature/recoverAddress.js'\nimport type {\n Authorization,\n SignedAuthorization,\n} from '../types/authorization.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf = OneOf<\n Authorization | SignedAuthorization\n >,\n //\n _signature = Hex | ByteArray | OneOf,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization: authorization | OneOf\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf,\n>(\n parameters: RecoverAuthorizationAddressParameters,\n): Promise {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as Authorization),\n signature: (signature ?? authorization) as Signature,\n })\n}\n","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n | HexToNumberErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\n )\n }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n }) {\n let identifier = 'Block'\n if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n super(`${identifier} could not be found.`, { name: 'BlockNotFoundError' })\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { SignedAuthorizationList } from '../../experimental/eip7702/types/authorization.js'\nimport type { RpcAuthorizationList } from '../../experimental/eip7702/types/rpc.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n | 'blockHash'\n | 'blockNumber'\n | 'transactionIndex'\n\nexport type FormattedTransaction<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(transaction: ExactPartial) {\n const transaction_ = {\n ...transaction,\n blockHash: transaction.blockHash ? transaction.blockHash : null,\n blockNumber: transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null,\n chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : undefined,\n maxFeePerGas: transaction.maxFeePerGas\n ? BigInt(transaction.maxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n ? BigInt(transaction.maxPriorityFeePerGas)\n : undefined,\n nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n to: transaction.to ? transaction.to : null,\n transactionIndex: transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null,\n type: transaction.type\n ? (transactionType as any)[transaction.type]\n : undefined,\n typeHex: transaction.type ? transaction.type : undefined,\n value: transaction.value ? BigInt(transaction.value) : undefined,\n v: transaction.v ? BigInt(transaction.v) : undefined,\n } as Transaction\n\n if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\n\n transaction_.yParity = (() => {\n // If `yParity` is provided, we will use it.\n if (transaction.yParity) return Number(transaction.yParity)\n\n // If no `yParity` provided, try derive from `v`.\n if (typeof transaction_.v === 'bigint') {\n if (transaction_.v === 0n || transaction_.v === 27n) return 0\n if (transaction_.v === 1n || transaction_.v === 28n) return 1\n if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n }\n\n return undefined\n })()\n\n if (transaction_.type === 'legacy') {\n delete transaction_.accessList\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') {\n delete transaction_.maxFeePerBlobGas\n }\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map(\n (authorization) =>\n ({\n contractAddress: (authorization as any).address,\n r: authorization.r,\n s: authorization.s,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: Number(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: Number(authorization.v) }\n : {}),\n }) as any,\n ) as SignedAuthorizationList\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { ExactPartial, Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(block: ExactPartial) {\n const transactions = block.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n return formatTransaction(transaction)\n })\n return {\n ...block,\n baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : undefined,\n gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n hash: block.hash ? block.hash : null,\n logsBloom: block.logsBloom ? block.logsBloom : null,\n nonce: block.nonce ? block.nonce : null,\n number: block.number ? BigInt(block.number) : null,\n size: block.size ? BigInt(block.size) : undefined,\n timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n transactions,\n totalDifficulty: block.totalDifficulty\n ? BigInt(block.totalDifficulty)\n : null,\n } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetBlockErrorType =\n | BlockNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks\n * - JSON-RPC Methods:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n * - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n includeTransactions: includeTransactions_,\n }: GetBlockParameters = {},\n): Promise> {\n const blockTag = blockTag_ ?? 'latest'\n const includeTransactions = includeTransactions_ ?? false\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let block: RpcBlock | null = null\n if (blockHash) {\n block = await client.request(\n {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n const format = client.chain?.formatters?.block?.format || formatBlock\n return format(block)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client): Promise {\n const gasPrice = await client.request({\n method: 'eth_gasPrice',\n })\n return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Chain, ChainFeesFnParameters } from '../../types/chain.js'\nimport type { GetChainParameter } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToBigIntErrorType,\n hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChainParameter\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n | GetBlockErrorType\n | HexToBigIntErrorType\n | RequestErrorType\n | GetBlockErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args?:\n | EstimateMaxPriorityFeePerGasParameters\n | undefined,\n): Promise {\n return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n>(\n client: Client,\n args: EstimateMaxPriorityFeePerGasParameters & {\n block?: Block | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\n const maxPriorityFeePerGasHex = await client.request({\n method: 'eth_maxPriorityFeePerGas',\n })\n return hexToBigInt(maxPriorityFeePerGasHex)\n } catch {\n // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n const [block, gasPrice] = await Promise.all([\n block_\n ? Promise.resolve(block_)\n : getAction(client, getBlock, 'getBlock')({}),\n getAction(client, getGasPrice, 'getGasPrice')({}),\n ])\n\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n if (maxPriorityFeePerGas < 0n) return 0n\n return maxPriorityFeePerGas\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesLegacy,\n FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n type EstimateMaxPriorityFeePerGasErrorType,\n internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n type extends FeeValuesType = FeeValuesType,\n> = {\n /**\n * The type of fee values to return.\n *\n * - `legacy`: Returns the legacy gas price.\n * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n *\n * @default 'eip1559'\n */\n type?: type | FeeValuesType | undefined\n} & GetChainParameter\n\nexport type EstimateFeesPerGasReturnType<\n type extends FeeValuesType = FeeValuesType,\n> =\n | (type extends 'legacy' ? FeeValuesLegacy : never)\n | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n | BaseFeeScalarErrorType\n | EstimateMaxPriorityFeePerGasErrorType\n | GetGasPriceErrorType\n | Eip1559FeesNotSupportedErrorType\n | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args?: EstimateFeesPerGasParameters | undefined,\n): Promise> {\n return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n chain extends Chain | undefined,\n chainOverride extends Chain | undefined,\n type extends FeeValuesType = 'eip1559',\n>(\n client: Client,\n args: EstimateFeesPerGasParameters & {\n block?: Block | undefined\n request?: PrepareTransactionRequestParameters | undefined\n },\n): Promise> {\n const {\n block: block_,\n chain = client.chain,\n request,\n type = 'eip1559',\n } = args || {}\n\n const baseFeeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n return chain.fees.baseFeeMultiplier({\n block: block_ as Block,\n client,\n request,\n } as ChainFeesFnParameters)\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiply = (base: bigint) =>\n (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n BigInt(denominator)\n\n const block = block_\n ? block_\n : await getAction(client, getBlock, 'getBlock')({})\n\n if (typeof chain?.fees?.estimateFeesPerGas === 'function') {\n const fees = (await chain.fees.estimateFeesPerGas({\n block: block_ as Block,\n client,\n multiply,\n request,\n type,\n } as ChainEstimateFeesPerGasFnParameters)) as unknown as EstimateFeesPerGasReturnType\n\n if (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client,\n {\n block: block as Block,\n chain,\n request,\n },\n )\n\n const baseFeePerGas = multiply(block.baseFeePerGas)\n const maxFeePerGas =\n request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as EstimateFeesPerGasReturnType\n }\n\n const gasPrice =\n request?.gasPrice ??\n multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n return {\n gasPrice,\n } as EstimateFeesPerGasReturnType\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError extends BaseError {\n override cause: BaseError\n\n constructor(\n cause: BaseError,\n {\n account,\n docsPath,\n chain,\n data,\n gas,\n gasPrice,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n }: Omit, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value:\n typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice:\n typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas:\n typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas:\n typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n })\n\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Estimate Gas Arguments:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'EstimateGasExecutionError',\n })\n this.cause = cause\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBalanceParameters = {\n /** The address of the account. */\n address: Address\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The balance of the account at a block tag. */\n blockTag?: BlockTag | undefined\n }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).\n *\n * ```ts\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const balance = await getBalance(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance(\n client: Client,\n { address, blockNumber, blockTag = 'latest' }: GetBalanceParameters,\n): Promise {\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n\n const balance = await client.request({\n method: 'eth_getBalance',\n params: [address, blockNumberHex || blockTag],\n })\n return BigInt(balance)\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../experimental/eip7702/utils/recoverAuthorizationAddress.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type GetEstimateGasErrorReturnType,\n getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\nimport { getBalance } from './getBalance.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit, 'from'> & {\n account?: Account | Address | undefined\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedEstimateGas =\n FormattedTransactionRequest\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\n | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n args: EstimateGasParameters,\n): Promise {\n const account_ = args.account ?? client.account\n const account = account_ ? parseAccount(account_) : undefined\n\n try {\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = (await prepareTransactionRequest(client, {\n ...args,\n parameters:\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n account?.type === 'local' ? undefined : ['blobVersionedHashes'],\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters\n\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\n\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (rest.to) return rest.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (authorizationList && authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n assertRequest(args as AssertRequestParameters)\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format({\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n from: account?.address,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest)\n\n function estimateGas_rpc(parameters: {\n block: any\n request: any\n rpcStateOverride: any\n }) {\n const { block, request, rpcStateOverride } = parameters\n return client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [request, block ?? 'latest', rpcStateOverride]\n : block\n ? [request, block]\n : [request],\n })\n }\n\n let estimate = BigInt(\n await estimateGas_rpc({ block, request, rpcStateOverride }),\n )\n\n // TODO(7702): Remove this once https://github.com/ethereum/execution-apis/issues/561 is resolved.\n // Authorization list schema is not implemented on JSON-RPC spec yet, so we need to\n // manually estimate the gas.\n if (authorizationList) {\n const value = await getBalance(client, { address: request.from })\n const estimates = await Promise.all(\n authorizationList.map(async (authorization) => {\n const { contractAddress } = authorization\n const estimate = await estimateGas_rpc({\n block,\n request: {\n authorizationList: undefined,\n data,\n from: account?.address,\n to: contractAddress,\n value: numberToHex(value),\n },\n rpcStateOverride,\n }).catch(() => 100_000n)\n return 2n * BigInt(estimate)\n }),\n )\n estimate += estimates.reduce((acc, curr) => acc + curr, 0n)\n }\n\n return estimate\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './getNodeError.js'\n\nexport type GetEstimateGasErrorReturnType = Omit<\n EstimateGasExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError>(\n err: err,\n {\n docsPath,\n ...args\n }: Omit & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n): GetEstimateGasErrorReturnType {\n const cause = (() => {\n const cause = getNodeError(\n err as {} as BaseError,\n args as GetNodeErrorParameters,\n )\n if (cause instanceof UnknownNodeError) return err as {} as BaseError\n return cause\n })()\n return new EstimateGasExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetEstimateGasErrorReturnType\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type HexToNumberErrorType,\n hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n /** The account address. */\n address: Address\n} & (\n | {\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\n }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n * address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [address, blockNumber ? numberToHex(blockNumber) : blockTag],\n },\n { dedupe: Boolean(blockNumber) },\n )\n return hexToNumber(count)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters,\n): BlobsToCommitmentsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters,\n): blobsToProofsReturnType {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters,\n): CommitmentToVersionedHashReturnType {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType\n}\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Sha256Hash =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash\n return toHex(bytes) as Sha256Hash\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType =\n | (to extends 'bytes' ? BlobSidecars : never)\n | (to extends 'hex' ? BlobSidecars : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters,\n): ToBlobSidecarsReturnType {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters): ToBlobsReturnType {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n type EstimateFeesPerGasErrorType,\n internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n type EstimateGasErrorType,\n type EstimateGasParameters,\n estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n type GetBlockErrorType,\n getBlock as getBlock_,\n} from '../../actions/public/getBlock.js'\nimport {\n type GetTransactionCountErrorType,\n getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type { GetChainParameter } from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType extends 'legacy'\n ? unknown\n : GetTransactionType,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick)\n>\n\nexport type PrepareTransactionRequestErrorType =\n | AccountNotFoundErrorType\n | AssertRequestErrorType\n | ParseAccountErrorType\n | GetBlockErrorType\n | GetTransactionCountErrorType\n | EstimateGasErrorType\n | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n const {\n account: account_ = client.account,\n blobs,\n chain,\n gas,\n kzg,\n nonce,\n nonceManager,\n parameters = defaultParameters,\n type,\n } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n const request = { ...args, ...(account ? { from: account?.address } : {}) }\n\n let block: Block | undefined\n async function getBlock(): Promise {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n let chainId: number | undefined\n async function getChainId(): Promise {\n if (chainId) return chainId\n if (chain) return chain.id\n if (typeof args.chainId !== 'undefined') return args.chainId\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (parameters.includes('nonce') && typeof nonce === 'undefined' && account) {\n if (nonceManager) {\n const chainId = await getChainId()\n request.nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n } else {\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n }\n }\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n // infer type from block\n const block = await getBlock()\n request.type =\n typeof block?.baseFeePerGas === 'bigint' ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof args.maxPriorityFeePerGas === 'undefined' &&\n args.maxFeePerGas &&\n args.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof args.maxFeePerGas !== 'undefined' ||\n typeof args.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account: account\n ? { address: account.address, type: 'json-rpc' }\n : undefined,\n } as EstimateGasParameters)\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters,\n): CommitmentsToVersionedHashesReturnType {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestGeneric,\n TransactionRequestLegacy,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport type {\n Assign,\n ExactPartial,\n IsNever,\n OneOf,\n ValueOf,\n} from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends\n | MatchKeys\n | MatchKeys\n | LegacyProperties\n ? 'legacy'\n : never)\n | (transaction extends\n | MatchKeys\n | MatchKeys\n | EIP1559Properties\n ? 'eip1559'\n : never)\n | (transaction extends\n | MatchKeys\n | MatchKeys\n | EIP2930Properties\n ? 'eip2930'\n : never)\n | (transaction extends\n | MatchKeys\n | MatchKeys\n | EIP4844Properties\n ? 'eip4844'\n : never)\n | (transaction extends\n | MatchKeys\n | MatchKeys\n | EIP7702Properties\n ? 'eip7702'\n : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract\n : never),\n> = IsNever extends true\n ? string\n : IsNever extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType {\n if (transaction.type)\n return transaction.type as GetTransactionType\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype MatchKeys = ValueOf<\n Required<{\n [K in keyof U]: K extends keyof T ? K : undefined\n }>\n> extends string\n ? T\n : never\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n BaseProperties,\n ExactPartial & {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n BaseProperties,\n ExactPartial &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n BaseProperties,\n ExactPartial & {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction(\n client: Client,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignTransactionErrorType } from '../../accounts/utils/signTransaction.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n AccountNotFoundError,\n type AccountNotFoundErrorType,\n AccountTypeNotSupportedError,\n type AccountTypeNotSupportedErrorType,\n} from '../../errors/account.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../experimental/eip7702/utils/recoverAuthorizationAddress.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type { GetChainParameter } from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type AssertCurrentChainErrorType,\n assertCurrentChain,\n} from '../../utils/chain/assertCurrentChain.js'\nimport {\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport { type GetChainIdErrorType, getChainId } from '../public/getChainId.js'\nimport {\n type PrepareTransactionRequestErrorType,\n defaultParameters,\n prepareTransactionRequest,\n} from './prepareTransactionRequest.js'\nimport {\n type SendRawTransactionErrorType,\n sendRawTransaction,\n} from './sendRawTransaction.js'\n\nexport type SendTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'> &\n GetTransactionRequestKzgParameter\n\nexport type SendTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n request extends SendTransactionRequest<\n chain,\n chainOverride\n > = SendTransactionRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter\n\nexport type SendTransactionReturnType = Hash\n\nexport type SendTransactionErrorType =\n | ParseAccountErrorType\n | GetTransactionErrorReturnType<\n | AccountNotFoundErrorType\n | AccountTypeNotSupportedErrorType\n | AssertCurrentChainErrorType\n | AssertRequestErrorType\n | GetChainIdErrorType\n | PrepareTransactionRequestErrorType\n | SendRawTransactionErrorType\n | RecoverAuthorizationAddressErrorType\n | SignTransactionErrorType\n | RequestErrorType\n >\n | ErrorType\n\n/**\n * Creates, signs, and sends a new transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendTransaction\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_sendTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction)\n * - Local Accounts: [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction)\n *\n * @param client - Client to use\n * @param parameters - {@link SendTransactionParameters}\n * @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link SendTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const hash = await sendTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 1000000000000000000n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { sendTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const hash = await sendTransaction(client, {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 1000000000000000000n,\n * })\n */\nexport async function sendTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionRequest,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client,\n parameters: SendTransactionParameters,\n): Promise {\n const {\n account: account_ = client.account,\n chain = client.chain,\n accessList,\n authorizationList,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n ...rest\n } = parameters\n\n if (!account_)\n throw new AccountNotFoundError({\n docsPath: '/docs/actions/wallet/sendTransaction',\n })\n const account = parseAccount(account_)\n\n try {\n assertRequest(parameters as AssertRequestParameters)\n\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (parameters.to) return parameters.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (authorizationList && authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`.',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n if (account.type === 'json-rpc') {\n let chainId: number | undefined\n if (chain !== null) {\n chainId = await getAction(client, getChainId, 'getChainId')({})\n assertCurrentChain({\n currentChainId: chainId,\n chain,\n })\n }\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format({\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n authorizationList,\n blobs,\n chainId,\n data,\n from: account.address,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest)\n return await client.request(\n {\n method: 'eth_sendTransaction',\n params: [request],\n },\n { retryCount: 0 },\n )\n }\n\n if (account.type === 'local') {\n // Prepare the request for signing (assign appropriate fees, etc.)\n const request = await getAction(\n client,\n prepareTransactionRequest,\n 'prepareTransactionRequest',\n )({\n account,\n accessList,\n authorizationList,\n blobs,\n chain,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n nonceManager: account.nonceManager,\n parameters: [...defaultParameters, 'sidecars'],\n value,\n ...rest,\n to,\n } as any)\n\n const serializer = chain?.serializers?.transaction\n const serializedTransaction = (await account.signTransaction(request, {\n serializer,\n })) as Hash\n return await getAction(\n client,\n sendRawTransaction,\n 'sendRawTransaction',\n )({\n serializedTransaction,\n })\n }\n\n if (account.type === 'smart')\n throw new AccountTypeNotSupportedError({\n metaMessages: [\n 'Consider using the `sendUserOperation` Action instead.',\n ],\n docsPath: '/docs/actions/bundler/sendUserOperation',\n type: 'smart',\n })\n\n throw new AccountTypeNotSupportedError({\n docsPath: '/docs/actions/wallet/sendTransaction',\n type: (account as { type: string }).type,\n })\n } catch (err) {\n if (err instanceof AccountTypeNotSupportedError) throw err\n throw getTransactionError(err as BaseError, {\n ...parameters,\n account,\n chain: parameters.chain || undefined,\n })\n }\n}\n","import {\n ChainMismatchError,\n type ChainMismatchErrorType,\n ChainNotFoundError,\n type ChainNotFoundErrorType,\n} from '../../errors/chain.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nexport type AssertCurrentChainParameters = {\n chain?: Chain | undefined\n currentChainId: number\n}\n\nexport type AssertCurrentChainErrorType =\n | ChainNotFoundErrorType\n | ChainMismatchErrorType\n | ErrorType\n\nexport function assertCurrentChain({\n chain,\n currentChainId,\n}: AssertCurrentChainParameters): void {\n if (!chain) throw new ChainNotFoundError()\n if (currentChainId !== chain.id)\n throw new ChainMismatchError({ chain, currentChainId })\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport {\n TransactionExecutionError,\n type TransactionExecutionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './getNodeError.js'\n\nexport type GetTransactionErrorParameters = Omit<\n SendTransactionParameters,\n 'account' | 'chain'\n> & {\n account: Account\n chain?: Chain | undefined\n docsPath?: string | undefined\n}\n\nexport type GetTransactionErrorReturnType = Omit<\n TransactionExecutionErrorType,\n 'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getTransactionError>(\n err: err,\n { docsPath, ...args }: GetTransactionErrorParameters,\n): GetTransactionErrorReturnType {\n const cause = (() => {\n const cause = getNodeError(\n err as {} as BaseError,\n args as GetNodeErrorParameters,\n )\n if (cause instanceof UnknownNodeError) return err as {} as BaseError\n return cause\n })()\n return new TransactionExecutionError(cause, {\n docsPath,\n ...args,\n }) as GetTransactionErrorReturnType\n}\n","import type { LiFiStep, Process } from '@lifi/types'\nimport { formatUnits } from 'viem'\nimport { config } from '../config.js'\n\nexport const getTransactionNotSentMessage = async (\n step?: LiFiStep,\n process?: Process\n): Promise => {\n let transactionNotSend =\n 'Transaction was not sent, your funds are still in your wallet'\n\n // add information about funds if available\n if (step) {\n const chain = await config.getChainById(step.action.fromChainId)\n\n transactionNotSend += ` (${formatUnits(\n BigInt(step.action.fromAmount),\n step.action.fromToken.decimals\n )} ${step.action.fromToken.symbol} on ${chain.name})`\n }\n\n transactionNotSend +=\n \", please retry.
If it still doesn't work, it is safe to delete this transfer and start a new one.\"\n\n // add transaction explorer link if available\n transactionNotSend +=\n process && process.txLink\n ? `
You can check the failed transaction 
here.`\n : ''\n\n return transactionNotSend\n}\n\nexport const getTransactionFailedMessage = async (\n step: LiFiStep,\n txLink?: string\n): Promise => {\n const chain = await config.getChainById(step.action.toChainId)\n\n const baseString = `It appears that your transaction may not have been successful.\n However, to confirm this, please check your ${chain.name} wallet for ${step.action.toToken.symbol}.`\n return txLink\n ? `${baseString}\n You can also check the block explorer for more information.`\n : baseString\n}\n","import {\n type ProcessStatus,\n type ProcessType,\n type StatusMessage,\n type Substatus,\n} from '@lifi/types'\n\nconst processMessages: Record<\n ProcessType,\n Partial>\n> = {\n TOKEN_ALLOWANCE: {\n STARTED: 'Setting token allowance.',\n PENDING: 'Waiting for token allowance.',\n DONE: 'Token allowance set.',\n },\n SWITCH_CHAIN: {\n PENDING: 'Chain switch required.',\n DONE: 'Chain switched successfully.',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction.',\n ACTION_REQUIRED: 'Please sign the transaction.',\n PENDING: 'Waiting for swap transaction.',\n DONE: 'Swap completed.',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction.',\n ACTION_REQUIRED: 'Please sign the transaction.',\n PENDING: 'Waiting for bridge transaction.',\n DONE: 'Bridge transaction confirmed.',\n },\n RECEIVING_CHAIN: {\n PENDING: 'Waiting for destination chain.',\n DONE: 'Bridge completed.',\n },\n TRANSACTION: {},\n}\nconst substatusMessages: Record<\n StatusMessage,\n Partial>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getProcessMessage(\n type: ProcessType,\n status: ProcessStatus\n): string | undefined {\n const processMessage = processMessages[type][status]\n return processMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n","import type {\n ChainId,\n Execution,\n ExecutionStatus,\n LiFiStep,\n Process,\n ProcessStatus,\n ProcessType,\n} from '@lifi/types'\nimport { executionState } from './executionState.js'\nimport { getProcessMessage } from './processMessages.js'\nimport type { LiFiStepExtended } from './types.js'\n\nexport type FindOrCreateProcessProps = {\n step: LiFiStepExtended\n type: ProcessType\n chainId?: ChainId\n status?: ProcessStatus\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking processes\n * @param {string} routeId The route dd this StatusManger belongs to.\n * @returns {StatusManager} An instance of StatusManager.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step and a function to update this step\n */\n initExecutionObject = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n status: 'PENDING',\n process: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.status = 'PENDING'\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param status The status for the execution\n * @param execution Optional. Information about received tokens\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n status: ExecutionStatus,\n execution?: Partial\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution.status = status\n if (execution) {\n step.execution = {\n ...step.execution,\n ...execution,\n }\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Create and push a new process into the execution.\n * @param step.step The step that should contain the new process.\n * @param step.type Type of the process. Used to identify already existing processes.\n * @param step.chainId Chain Id of the process.\n * @param step.status By default created procces is set to the STARTED status. We can override new process with the needed status.\n * @param root0\n * @param root0.step\n * @param root0.type\n * @param root0.chainId\n * @param root0.status\n * @returns Returns process.\n */\n findOrCreateProcess = ({\n step,\n type,\n chainId,\n status,\n }: FindOrCreateProcessProps): Process => {\n if (!step.execution?.process) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const process = step.execution.process.find((p) => p.type === type)\n\n if (process) {\n if (status && process.status !== status) {\n process.status = status\n this.updateStepInRoute(step)\n }\n return process\n }\n\n const newProcess: Process = {\n type: type,\n startedAt: Date.now(),\n message: getProcessMessage(type, status ?? 'STARTED'),\n status: status ?? 'STARTED',\n chainId: chainId,\n }\n\n step.execution.process.push(newProcess)\n this.updateStepInRoute(step)\n return newProcess\n }\n\n /**\n * Update a process object.\n * @param step The step where the process should be updated\n * @param type The process type to update\n * @param status The status the process gets.\n * @param [params] Additional parameters to append to the process.\n * @returns The update process\n */\n updateProcess = (\n step: LiFiStepExtended,\n type: ProcessType,\n status: ProcessStatus,\n params?: Partial\n ): Process => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentProcess = step?.execution?.process.find((p) => p.type === type)\n\n if (!currentProcess) {\n throw new Error(\"Can't find a process for the given type.\")\n }\n\n switch (status) {\n case 'CANCELLED':\n currentProcess.doneAt = Date.now()\n break\n case 'FAILED':\n currentProcess.doneAt = Date.now()\n step.execution.status = 'FAILED'\n break\n case 'DONE':\n currentProcess.doneAt = Date.now()\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n break\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentProcess.status = status\n currentProcess.message = getProcessMessage(type, status)\n // set extra parameters or overwritte the standard params set in the switch statement\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n currentProcess[key] = value\n }\n }\n // Sort processes, the ones with DONE status go first\n step.execution.process = [\n ...step?.execution?.process.filter(\n (process) => process.status === 'DONE'\n ),\n ...step?.execution?.process.filter(\n (process) => process.status !== 'DONE'\n ),\n ]\n this.updateStepInRoute(step) // updates the step in the route\n return currentProcess\n }\n\n /**\n * Remove a process from the execution\n * @param step The step where the process should be removed from\n * @param type The process type to remove\n */\n removeProcess = (step: LiFiStepExtended, type: ProcessType): void => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n const index = step.execution.process.findIndex((p) => p.type === type)\n step.execution.process.splice(index, 1)\n this.updateStepInRoute(step)\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n }\n}\n","import type { LiFiStep } from '@lifi/types'\nimport { StatusManager } from './StatusManager.js'\nimport type {\n ExecutionOptions,\n InteractionSettings,\n StepExecutor,\n StepExecutorOptions,\n} from './types.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n abstract executeStep(step: LiFiStep): Promise\n}\n","import { type LiFiStep } from '@lifi/types'\n\n/**\n * Used to check if changed exchange rate is in the range of slippage threshold.\n * We use a slippage value as a threshold to trigger the rate change hook.\n * This can result in almost doubled slippage for the user and need to be revisited.\n * @param oldStep - old step\n * @param newStep - new step\n * @returns Boolean\n */\nexport function checkStepSlippageThreshold(\n oldStep: LiFiStep,\n newStep: LiFiStep\n): boolean {\n const setSlippage = oldStep.action.slippage\n const oldEstimatedToAmount = BigInt(oldStep.estimate.toAmountMin)\n const newEstimatedToAmount = BigInt(newStep.estimate.toAmountMin)\n const amountDifference = oldEstimatedToAmount - newEstimatedToAmount\n // oldEstimatedToAmount can be 0 when we use contract calls\n let actualSlippage = 0\n if (oldEstimatedToAmount > 0) {\n actualSlippage =\n Number((amountDifference * 1_000_000_000n) / oldEstimatedToAmount) /\n 1_000_000_000\n }\n return actualSlippage <= setSlippage\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolve) => {\n setTimeout(() => resolve(null), ms)\n })\n}\n","import type { LiFiStep } from '@lifi/types'\nimport { formatUnits } from 'viem'\nimport { getTokenBalance } from '../services/balance.js'\nimport { BalanceError } from '../errors/errors.js'\nimport { sleep } from './utils.js'\n\nexport const checkBalance = async (\n walletAddress: string,\n step: LiFiStep,\n depth = 0\n): Promise => {\n const token = await getTokenBalance(walletAddress, step.action.fromToken)\n if (token) {\n const currentBalance = token.amount ?? 0n\n const neededBalance = BigInt(step.action.fromAmount)\n\n if (currentBalance < neededBalance) {\n if (depth <= 3) {\n await sleep(200)\n await checkBalance(walletAddress, step, depth + 1)\n } else if (\n (neededBalance * BigInt((1 - step.action.slippage) * 1_000_000_000)) /\n 1_000_000_000n <=\n currentBalance\n ) {\n // adjust amount in slippage limits\n step.action.fromAmount = currentBalance.toString()\n } else {\n const neeeded = formatUnits(neededBalance, token.decimals)\n const current = formatUnits(currentBalance, token.decimals)\n let errorMessage =\n `Your ${token.symbol} balance is too low, ` +\n `you try to transfer ${neeeded} ${token.symbol}, ` +\n `but your wallet only holds ${current} ${token.symbol}. ` +\n `No funds have been sent.`\n\n if (currentBalance !== 0n) {\n errorMessage +=\n `If the problem consists, please delete this transfer and ` +\n `start a new one with a maximum of ${current} ${token.symbol}.`\n }\n\n throw new BalanceError('The balance is too low.')\n }\n }\n }\n}\n","import type { LiFiStep } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { TransactionError } from '../errors/errors.js'\nimport type { StatusManager } from './StatusManager.js'\nimport type { ExecutionOptions } from './types.js'\nimport { checkStepSlippageThreshold } from './utils.js'\n\n/**\n * This method checks whether the new and updated Step meets the required exchange rate conditions.\n * If yes it returns the updated Step.\n * If no and if user interaction is allowed it triggers the acceptExchangeRateUpdateHook. If no user interaction is allowed it aborts.\n * @param statusManager\n * @param oldStep\n * @param newStep\n * @param settings\n * @param allowUserInteraction\n * @param executionOptions\n * @returns Return LiFiStep\n */\nexport const stepComparison = async (\n statusManager: StatusManager,\n oldStep: LiFiStep,\n newStep: LiFiStep,\n allowUserInteraction: boolean,\n executionOptions?: ExecutionOptions\n): Promise => {\n // Check if changed exchange rate is in the range of slippage threshold\n if (checkStepSlippageThreshold(oldStep, newStep)) {\n return statusManager.updateStepInRoute(newStep)\n }\n\n let allowStepUpdate: boolean | undefined\n if (allowUserInteraction) {\n allowStepUpdate = await executionOptions?.acceptExchangeRateUpdateHook?.({\n oldToAmount: oldStep.estimate.toAmount,\n newToAmount: newStep.estimate.toAmount,\n toToken: newStep.action.toToken,\n })\n }\n\n if (!allowStepUpdate) {\n // The user declined the new exchange rate, so we are not going to proceed\n throw new TransactionError(\n LiFiErrorCode.ExchangeRateUpdateCanceled,\n `Exchange rate has changed!\\nTransaction was not sent, your funds are still in your wallet.\\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.`\n )\n }\n\n return statusManager.updateStepInRoute(newStep)\n}\n","import type {\n FullStatusData,\n LiFiStep,\n ProcessType,\n StatusResponse,\n} from '@lifi/types'\nimport { getStatus } from '../services/api.js'\nimport { ServerError } from '../errors/errors.js'\nimport { repeatUntilDone } from '../utils/utils.js'\nimport type { StatusManager } from './StatusManager.js'\nimport { getSubstatusMessage } from './processMessages.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record> = {}\n\nexport async function waitForReceivingTransaction(\n txHash: string,\n statusManager: StatusManager,\n processType: ProcessType,\n step: LiFiStep\n): Promise {\n const _getStatus = (): Promise =>\n new Promise(async (resolve, reject) => {\n let statusResponse: StatusResponse\n try {\n statusResponse = await getStatus({\n fromChain: step.action.fromChainId,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n })\n } catch (e: any) {\n console.debug('Fetching status from backend failed.', e)\n return resolve(undefined)\n }\n\n switch (statusResponse.status) {\n case 'DONE':\n return resolve(statusResponse)\n case 'PENDING':\n statusManager?.updateProcess(step, processType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return resolve(undefined)\n case 'NOT_FOUND':\n return resolve(undefined)\n case 'INVALID':\n case 'FAILED':\n default:\n return reject()\n }\n })\n\n let status\n\n if (txHash in TRANSACTION_HASH_OBSERVERS) {\n status = await TRANSACTION_HASH_OBSERVERS[txHash]\n } else {\n TRANSACTION_HASH_OBSERVERS[txHash] = repeatUntilDone(_getStatus, 5_000)\n status = await TRANSACTION_HASH_OBSERVERS[txHash]\n }\n\n if (!('receiving' in status)) {\n throw new ServerError(\"Status doesn't contain receiving information.\")\n }\n\n return status\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n | -1\n | -32700 // Parse error\n | -32600 // Invalid request\n | -32601 // Method not found\n | -32602 // Invalid params\n | -32603 // Internal error\n | -32000 // Invalid input\n | -32001 // Resource not found\n | -32002 // Resource unavailable\n | -32003 // Transaction rejected\n | -32004 // Method not supported\n | -32005 // Limit exceeded\n | -32006 // JSON-RPC version not supported\n | -32042 // Method not found\n\ntype RpcErrorOptions = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode\n ) as code_\n }\n}\n\nexport type ProviderRpcErrorCode =\n | 4001 // User Rejected Request\n | 4100 // Unauthorized\n | 4200 // Unsupported Method\n | 4900 // Disconnected\n | 4901 // Chain Disconnected\n | 4902 // Chain Not Recognized\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n T = undefined,\n> extends RpcError {\n data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions & {\n data?: T | undefined\n }\n >,\n ) {\n super(cause, options)\n\n this.data = options.data\n }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n code: -32700\n name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage:\n 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n })\n }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n code: -32600\n name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n code: -32601\n name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n code: -32602\n name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n code: -32603\n name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n })\n }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n code: -32000\n name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n })\n }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n code: -32001\n name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n override name = 'ResourceNotFoundRpcError'\n static code = -32001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n })\n }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n code: -32002\n name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n })\n }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n code: -32003\n name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n })\n }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n code: -32004\n name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not implemented.`,\n })\n }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n code: -32005\n name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n })\n }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n JsonRpcVersionUnsupportedError & {\n code: -32006\n name: 'JsonRpcVersionUnsupportedError'\n }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n })\n }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n code: 4001\n name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n code: 4100\n name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage:\n 'The requested method and/or account has not been authorized by the user.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n UnsupportedProviderMethodError & {\n code: 4200\n name: 'UnsupportedProviderMethodError'\n }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n })\n }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n code: 4900\n name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n })\n }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n code: 4901\n name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n code: 4902\n name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { InternalRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType = Omit<\n ContractFunctionExecutionErrorType,\n 'cause'\n> & {\n cause:\n | cause\n | ContractFunctionZeroDataErrorType\n | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError>(\n err: err,\n {\n abi,\n address,\n args,\n docsPath,\n functionName,\n sender,\n }: {\n abi: Abi\n args: any\n address?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const { code, data, message, shortMessage } = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as RawContractError\n\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName })\n if (\n [EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || message || shortMessage)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message: shortMessage ?? message,\n })\n }\n return err\n })()\n\n return new ContractFunctionExecutionError(cause as BaseError, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n }) as GetContractErrorReturnType\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'blockNumber'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs,\n> = ContractFunctionReturnType\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n const args extends ContractFunctionArgs,\n>(\n client: Client,\n parameters: ReadContractParameters,\n): Promise> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { Abi } from 'viem'\n\nexport const approveAbi: Abi = [\n {\n name: 'approve',\n inputs: [\n { internalType: 'address', name: 'spender', type: 'address' },\n { internalType: 'uint256', name: 'amount', type: 'uint256' },\n ],\n outputs: [{ internalType: 'bool', name: 'approved', type: 'bool' }],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n]\n\nexport const allowanceAbi: Abi = [\n {\n name: 'allowance',\n inputs: [\n { internalType: 'address', name: 'owner', type: 'address' },\n { internalType: 'address', name: 'spender', type: 'address' },\n ],\n outputs: [{ internalType: 'uint256', name: 'allowance', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n]\n\nexport const getEthBalanceAbi: Abi = [\n {\n inputs: [{ name: '_owner', type: 'address' }],\n name: 'getEthBalance',\n outputs: [{ name: 'balance', type: 'uint256' }],\n type: 'function',\n stateMutability: 'view',\n },\n]\n\nexport const balanceOfAbi: Abi = [\n {\n inputs: [{ name: '_owner', type: 'address' }],\n name: 'balanceOf',\n outputs: [{ name: 'balance', type: 'uint256' }],\n type: 'function',\n stateMutability: 'view',\n },\n]\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super(\n 'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout(\n fn: ({\n signal,\n }: { signal: AbortController['signal'] | null }) => Promise,\n {\n errorInstance = new Error('timed out'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') reject(errorInstance)\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit | undefined\n /** A callback to handle the request. */\n onRequest?: ((request: Request) => Promise | void) | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?: ((request: Request) => Promise | void) | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request(\n params: HttpRequestParameters,\n ): Promise>\n}\n\nexport function getHttpRpcClient(\n url: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n return {\n async request(params) {\n const {\n body,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n if (onRequest) await onRequest(request)\n const response = await fetch(url, init)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\n }\n\n if (!response.ok) {\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n })\n }\n\n return data\n } catch (err) {\n if (err instanceof HttpRequestError) throw err\n if (err instanceof TimeoutError) throw err\n throw new HttpRequestError({\n body,\n cause: err as Error,\n url,\n })\n }\n },\n }\n}\n","import { SocketClosedError, TimeoutError } from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport {\n type CreateBatchSchedulerErrorType,\n createBatchScheduler,\n} from '../promise/createBatchScheduler.js'\nimport { withTimeout } from '../promise/withTimeout.js'\nimport { idCache } from './id.js'\n\ntype Id = string | number\ntype CallbackFn = {\n onResponse: (message: any) => void\n onError?: ((error?: Error | Event | undefined) => void) | undefined\n}\ntype CallbackMap = Map\n\nexport type GetSocketParameters = {\n onClose: () => void\n onError: (error?: Error | Event | undefined) => void\n onOpen: () => void\n onResponse: (data: RpcResponse) => void\n}\n\nexport type Socket = socket & {\n close(): void\n ping?: (() => void) | undefined\n request(params: { body: RpcRequest }): void\n}\n\nexport type SocketRpcClient = {\n close(): void\n socket: Socket\n request(params: {\n body: RpcRequest\n onError?: ((error?: Error | Event | undefined) => void) | undefined\n onResponse: (message: RpcResponse) => void\n }): void\n requestAsync(params: {\n body: RpcRequest\n timeout?: number | undefined\n }): Promise\n requests: CallbackMap\n subscriptions: CallbackMap\n url: string\n}\n\nexport type GetSocketRpcClientParameters = {\n getSocket(params: GetSocketParameters): Promise>\n /**\n * Whether or not to send keep-alive messages.\n * @default true\n */\n keepAlive?:\n | boolean\n | {\n /**\n * The interval (in ms) to send keep-alive messages.\n * @default 30_000\n */\n interval?: number | undefined\n }\n | undefined\n key?: string\n /**\n * Whether or not to attempt to reconnect on socket failure or closure.\n * @default true\n */\n reconnect?:\n | boolean\n | {\n /**\n * The maximum number of reconnection attempts.\n * @default 5\n */\n attempts?: number | undefined\n /**\n * The delay (in ms) between reconnection attempts.\n * @default 2_000\n */\n delay?: number | undefined\n }\n | undefined\n url: string\n}\n\nexport type GetSocketRpcClientErrorType =\n | CreateBatchSchedulerErrorType\n | ErrorType\n\nexport const socketClientCache = /*#__PURE__*/ new Map<\n string,\n SocketRpcClient>\n>()\n\nexport async function getSocketRpcClient(\n parameters: GetSocketRpcClientParameters,\n): Promise> {\n const {\n getSocket,\n keepAlive = true,\n key = 'socket',\n reconnect = true,\n url,\n } = parameters\n const { interval: keepAliveInterval = 30_000 } =\n typeof keepAlive === 'object' ? keepAlive : {}\n const { attempts = 5, delay = 2_000 } =\n typeof reconnect === 'object' ? reconnect : {}\n\n let socketClient = socketClientCache.get(`${key}:${url}`)\n\n // If the socket already exists, return it.\n if (socketClient) return socketClient as {} as SocketRpcClient\n\n let reconnectCount = 0\n const { schedule } = createBatchScheduler<\n undefined,\n [SocketRpcClient]\n >({\n id: `${key}:${url}`,\n fn: async () => {\n // Set up a cache for incoming \"synchronous\" requests.\n const requests = new Map()\n\n // Set up a cache for subscriptions (eth_subscribe).\n const subscriptions = new Map()\n\n let error: Error | Event | undefined\n let socket: Socket<{}>\n let keepAliveTimer: Timer | undefined\n\n // Set up socket implementation.\n async function setup() {\n const result = await getSocket({\n onClose() {\n // Notify all requests and subscriptions of the closure error.\n for (const request of requests.values())\n request.onError?.(new SocketClosedError({ url }))\n for (const subscription of subscriptions.values())\n subscription.onError?.(new SocketClosedError({ url }))\n\n // Clear all requests and subscriptions.\n requests.clear()\n subscriptions.clear()\n\n // Attempt to reconnect.\n if (reconnect && reconnectCount < attempts)\n setTimeout(async () => {\n reconnectCount++\n await setup().catch(console.error)\n }, delay)\n },\n onError(error_) {\n error = error_\n\n // Notify all requests and subscriptions of the error.\n for (const request of requests.values()) request.onError?.(error)\n for (const subscription of subscriptions.values())\n subscription.onError?.(error)\n\n // Clear all requests and subscriptions.\n requests.clear()\n subscriptions.clear()\n\n // Attempt to reconnect.\n if (reconnect && reconnectCount < attempts)\n setTimeout(async () => {\n reconnectCount++\n await setup().catch(console.error)\n }, delay)\n },\n onOpen() {\n error = undefined\n reconnectCount = 0\n },\n onResponse(data) {\n const isSubscription = data.method === 'eth_subscription'\n const id = isSubscription ? data.params.subscription : data.id\n const cache = isSubscription ? subscriptions : requests\n const callback = cache.get(id)\n if (callback) callback.onResponse(data)\n if (!isSubscription) cache.delete(id)\n },\n })\n\n socket = result\n\n if (keepAlive) {\n if (keepAliveTimer) clearInterval(keepAliveTimer)\n keepAliveTimer = setInterval(() => socket.ping?.(), keepAliveInterval)\n }\n\n return result\n }\n await setup()\n error = undefined\n\n // Create a new socket instance.\n socketClient = {\n close() {\n keepAliveTimer && clearInterval(keepAliveTimer)\n socket.close()\n socketClientCache.delete(`${key}:${url}`)\n },\n get socket() {\n return socket\n },\n request({ body, onError, onResponse }) {\n if (error && onError) onError(error)\n\n const id = body.id ?? idCache.take()\n\n const callback = (response: RpcResponse) => {\n if (typeof response.id === 'number' && id !== response.id) return\n\n // If we are subscribing to a topic, we want to set up a listener for incoming\n // messages.\n if (\n body.method === 'eth_subscribe' &&\n typeof response.result === 'string'\n )\n subscriptions.set(response.result, {\n onResponse: callback,\n onError,\n })\n\n // If we are unsubscribing from a topic, we want to remove the listener.\n if (body.method === 'eth_unsubscribe')\n subscriptions.delete(body.params?.[0])\n\n onResponse(response)\n }\n\n requests.set(id, { onResponse: callback, onError })\n try {\n socket.request({\n body: {\n jsonrpc: '2.0',\n id,\n ...body,\n },\n })\n } catch (error) {\n onError?.(error as Error)\n }\n },\n requestAsync({ body, timeout = 10_000 }) {\n return withTimeout(\n () =>\n new Promise((onResponse, onError) =>\n this.request({\n body,\n onError,\n onResponse,\n }),\n ),\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n },\n )\n },\n requests,\n subscriptions,\n url,\n }\n socketClientCache.set(`${key}:${url}`, socketClient)\n\n return [socketClient as {} as SocketRpcClient]\n },\n })\n\n const [_, [socketClient_]] = await schedule()\n return socketClient_\n}\n","import type { MessageEvent } from 'isows'\n\nimport {\n SocketClosedError,\n WebSocketRequestError,\n} from '../../errors/request.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport {\n type GetSocketRpcClientParameters,\n type Socket,\n type SocketRpcClient,\n getSocketRpcClient,\n} from './socket.js'\n\nexport type GetWebSocketRpcClientOptions = Pick<\n GetSocketRpcClientParameters,\n 'keepAlive' | 'reconnect'\n>\n\nexport async function getWebSocketRpcClient(\n url: string,\n options: GetWebSocketRpcClientOptions | undefined = {},\n): Promise> {\n const { keepAlive, reconnect } = options\n\n return getSocketRpcClient({\n async getSocket({ onClose, onError, onOpen, onResponse }) {\n const WebSocket = await import('isows').then((module) => module.WebSocket)\n const socket = new WebSocket(url)\n\n function onClose_() {\n onClose()\n socket.removeEventListener('close', onClose_)\n socket.removeEventListener('message', onMessage)\n socket.removeEventListener('error', onError)\n socket.removeEventListener('open', onOpen)\n }\n function onMessage({ data }: MessageEvent) {\n onResponse(JSON.parse(data))\n }\n\n // Setup event listeners for RPC & subscription responses.\n socket.addEventListener('close', onClose_)\n socket.addEventListener('message', onMessage)\n socket.addEventListener('error', onError)\n socket.addEventListener('open', onOpen)\n\n // Wait for the socket to open.\n if (socket.readyState === WebSocket.CONNECTING) {\n await new Promise((resolve, reject) => {\n if (!socket) return\n socket.onopen = resolve\n socket.onerror = reject\n })\n }\n\n const { close: close_ } = socket\n\n return Object.assign(socket, {\n close() {\n close_.bind(socket)()\n onClose()\n },\n ping() {\n try {\n if (\n socket.readyState === socket.CLOSED ||\n socket.readyState === socket.CLOSING\n )\n throw new WebSocketRequestError({\n url: socket.url,\n cause: new SocketClosedError({ url: socket.url }),\n })\n\n const body: RpcRequest = {\n jsonrpc: '2.0',\n method: 'net_version',\n params: [],\n }\n socket.send(JSON.stringify(body))\n } catch (error) {\n onError(error as Error)\n }\n },\n request({ body }) {\n if (\n socket.readyState === socket.CLOSED ||\n socket.readyState === socket.CLOSING\n )\n throw new WebSocketRequestError({\n body,\n url: socket.url,\n cause: new SocketClosedError({ url: socket.url }),\n })\n\n return socket.send(JSON.stringify(body))\n },\n } as Socket)\n },\n keepAlive,\n reconnect,\n url,\n })\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe(\n fn: () => Promise,\n { enabled = true, id }: WithDedupeOptions,\n): Promise {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","export async function wait(time: number) {\n return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry(\n fn: () => Promise,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n const retry = async ({ error }: { error: Error }) => {\n const delay =\n typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n if (delay) await wait(delay)\n attemptRetry({ count: count + 1 })\n }\n\n try {\n const data = await fn()\n resolve(data)\n } catch (err) {\n if (\n count < retryCount &&\n (await shouldRetry({ count, error: err as Error }))\n )\n return retry({ error: err as Error })\n reject(err)\n }\n }\n attemptRetry()\n })\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n HttpRequestError,\n type HttpRequestErrorType,\n type RpcRequestErrorType,\n type TimeoutErrorType,\n type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n InternalRpcError,\n type InternalRpcErrorType,\n InvalidInputRpcError,\n type InvalidInputRpcErrorType,\n InvalidParamsRpcError,\n type InvalidParamsRpcErrorType,\n InvalidRequestRpcError,\n type InvalidRequestRpcErrorType,\n JsonRpcVersionUnsupportedError,\n type JsonRpcVersionUnsupportedErrorType,\n LimitExceededRpcError,\n type LimitExceededRpcErrorType,\n MethodNotFoundRpcError,\n type MethodNotFoundRpcErrorType,\n MethodNotSupportedRpcError,\n type MethodNotSupportedRpcErrorType,\n ParseRpcError,\n type ParseRpcErrorType,\n ProviderDisconnectedError,\n type ProviderDisconnectedErrorType,\n type ProviderRpcErrorCode,\n ResourceNotFoundRpcError,\n type ResourceNotFoundRpcErrorType,\n ResourceUnavailableRpcError,\n type ResourceUnavailableRpcErrorType,\n type RpcError,\n type RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n type SwitchChainErrorType,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport { keccak256 } from './hash/keccak256.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\n | JsonRpcVersionUnsupportedErrorType\n | LimitExceededRpcErrorType\n | MethodNotFoundRpcErrorType\n | MethodNotSupportedRpcErrorType\n | ParseRpcErrorType\n | ProviderDisconnectedErrorType\n | ResourceNotFoundRpcErrorType\n | ResourceUnavailableRpcErrorType\n | RpcErrorType\n | RpcRequestErrorType\n | SwitchChainErrorType\n | TimeoutErrorType\n | TransactionRejectedRpcErrorType\n | UnauthorizedProviderErrorType\n | UnknownRpcErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest Promise>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n const requestId = dedupe\n ? keccak256(stringToHex(`${uid}.${stringify(args)}`))\n : undefined\n return withDedupe(\n () =>\n withRetry(\n async () => {\n try {\n return await request(args)\n } catch (err_) {\n const err = err_ as unknown as RpcError<\n RpcErrorCode | ProviderRpcErrorCode\n >\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err)\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err)\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method })\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err)\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err)\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err)\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err)\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err)\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err)\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err)\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err)\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err)\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err)\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err)\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err)\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err)\n default:\n if (err_ instanceof BaseError) throw err_\n throw new UnknownRpcError(err as Error)\n }\n }\n },\n {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After')\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = ({\n chain,\n}: {\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n type extends string,\n rpcAttributes extends Record,\n>(\n {\n key,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig,\n value?: rpcAttributes | undefined,\n): ReturnType> {\n const uid = uid_()\n return {\n config: {\n key,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { retryCount, retryDelay, uid }),\n value,\n }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcResponse } from '../../types/rpc.js'\nimport { getSocket } from '../../utils/rpc/compat.js'\nimport type { SocketRpcClient } from '../../utils/rpc/socket.js'\nimport {\n type GetWebSocketRpcClientOptions,\n getWebSocketRpcClient,\n} from '../../utils/rpc/webSocket.js'\nimport {\n type CreateTransportErrorType,\n type Transport,\n type TransportConfig,\n createTransport,\n} from './createTransport.js'\n\ntype WebSocketTransportSubscribeParameters = {\n onData: (data: RpcResponse) => void\n onError?: ((error: any) => void) | undefined\n}\n\ntype WebSocketTransportSubscribeReturnType = {\n subscriptionId: Hash\n unsubscribe: () => Promise>\n}\n\ntype WebSocketTransportSubscribe = {\n subscribe(\n args: WebSocketTransportSubscribeParameters & {\n /**\n * @description Add information about compiled contracts\n * @link https://hardhat.org/hardhat-network/docs/reference#hardhat_addcompilationresult\n */\n params: ['newHeads']\n },\n ): Promise\n}\n\nexport type WebSocketTransportConfig = {\n /**\n * Whether or not to send keep-alive ping messages.\n * @default true\n */\n keepAlive?: GetWebSocketRpcClientOptions['keepAlive'] | undefined\n /** The key of the WebSocket transport. */\n key?: TransportConfig['key'] | undefined\n /** The name of the WebSocket transport. */\n name?: TransportConfig['name'] | undefined\n /**\n * Whether or not to attempt to reconnect on socket failure.\n * @default true\n */\n reconnect?: GetWebSocketRpcClientOptions['reconnect'] | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** The timeout (in ms) for async WebSocket requests. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type WebSocketTransport = Transport<\n 'webSocket',\n {\n /**\n * @deprecated use `getRpcClient` instead.\n */\n getSocket(): Promise\n getRpcClient(): Promise>\n subscribe: WebSocketTransportSubscribe['subscribe']\n }\n>\n\nexport type WebSocketTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a WebSocket transport that connects to a JSON-RPC API.\n */\nexport function webSocket(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string,\n config: WebSocketTransportConfig = {},\n): WebSocketTransport {\n const {\n keepAlive,\n key = 'webSocket',\n name = 'WebSocket JSON-RPC',\n reconnect,\n retryDelay,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.webSocket?.[0]\n if (!url_) throw new UrlRequiredError()\n return createTransport(\n {\n key,\n name,\n async request({ method, params }) {\n const body = { method, params }\n const rpcClient = await getWebSocketRpcClient(url_, {\n keepAlive,\n reconnect,\n })\n const { error, result } = await rpcClient.requestAsync({\n body,\n timeout,\n })\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'webSocket',\n },\n {\n getSocket() {\n return getSocket(url_)\n },\n getRpcClient() {\n return getWebSocketRpcClient(url_)\n },\n async subscribe({ params, onData, onError }: any) {\n const rpcClient = await getWebSocketRpcClient(url_)\n const { result: subscriptionId } = await new Promise(\n (resolve, reject) =>\n rpcClient.request({\n body: {\n method: 'eth_subscribe',\n params,\n },\n onError(error) {\n reject(error)\n onError?.(error)\n return\n },\n onResponse(response) {\n if (response.error) {\n reject(response.error)\n onError?.(response.error)\n return\n }\n\n if (typeof response.id === 'number') {\n resolve(response)\n return\n }\n if (response.method !== 'eth_subscription') return\n onData(response.params)\n },\n }),\n )\n return {\n subscriptionId,\n async unsubscribe() {\n return new Promise((resolve) =>\n rpcClient.request({\n body: {\n method: 'eth_unsubscribe',\n params: [subscriptionId],\n },\n onResponse: resolve,\n }),\n )\n },\n }\n },\n },\n )\n }\n}\n","// TODO(v3): This file is here for backwards compatibility, and to prevent breaking changes.\n// These APIs will be removed in v3.\n\n/* c8 ignore start */\nimport type {\n TimeoutErrorType,\n WebSocketRequestError,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcResponse } from '../../types/rpc.js'\nimport type { WithTimeoutErrorType } from '../promise/withTimeout.js'\nimport { type HttpRequestParameters, getHttpRpcClient } from './http.js'\nimport type { SocketRpcClient } from './socket.js'\nimport { getWebSocketRpcClient } from './webSocket.js'\n\nexport type WebSocketOptions = Parameters<\n SocketRpcClient['request']\n>[0]\nexport type WebSocketReturnType = SocketRpcClient\nexport type WebSocketErrorType = WebSocketRequestError | ErrorType\n\nfunction webSocket(\n socketClient: SocketRpcClient,\n { body, onError, onResponse }: WebSocketOptions,\n): WebSocketReturnType {\n socketClient.request({\n body,\n onError,\n onResponse,\n })\n return socketClient\n}\n\nexport type WebSocketAsyncOptions = Parameters<\n SocketRpcClient['requestAsync']\n>[0]\nexport type WebSocketAsyncReturnType = RpcResponse\nexport type WebSocketAsyncErrorType =\n | WebSocketErrorType\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nasync function webSocketAsync(\n socketClient: SocketRpcClient,\n { body, timeout = 10_000 }: WebSocketAsyncOptions,\n): Promise {\n return socketClient.requestAsync({\n body,\n timeout,\n })\n}\n\n/**\n * @deprecated use `getSocketClient` instead.\n *\n * ```diff\n * -import { getSocket } from 'viem/utils'\n * +import { getSocketClient } from 'viem/utils'\n *\n * -const socket = await getSocket(url)\n * +const socketClient = await getSocketClient(url)\n * +const socket = socketClient.socket\n * ```\n */\nexport async function getSocket(url: string) {\n const client = await getWebSocketRpcClient(url)\n return Object.assign(client.socket, {\n requests: client.requests,\n subscriptions: client.subscriptions,\n })\n}\n\nexport const rpc = {\n /**\n * @deprecated use `getHttpRpcClient` instead.\n *\n * ```diff\n * -import { rpc } from 'viem/utils'\n * +import { getHttpRpcClient } from 'viem/utils'\n *\n * -rpc.http(url, params)\n * +const httpClient = getHttpRpcClient(url)\n * +httpClient.request(params)\n * ```\n */\n http(url: string, params: HttpRequestParameters) {\n return getHttpRpcClient(url).request(params)\n },\n /**\n * @deprecated use `getWebSocketRpcClient` instead.\n *\n * ```diff\n * -import { rpc } from 'viem/utils'\n * +import { getWebSocketRpcClient } from 'viem/utils'\n *\n * -rpc.webSocket(url, params)\n * +const webSocketClient = getWebSocketRpcClient(url)\n * +webSocketClient.request(params)\n * ```\n */\n webSocket,\n /**\n * @deprecated use `getWebSocketRpcClient` instead.\n *\n * ```diff\n * -import { rpc } from 'viem/utils'\n * +import { getWebSocketRpcClient } from 'viem/utils'\n *\n * -const response = await rpc.webSocketAsync(url, params)\n * +const webSocketClient = getWebSocketRpcClient(url)\n * +const response = await webSocketClient.requestAsync(params)\n * ```\n */\n webSocketAsync,\n}\n/* c8 ignore end */\n","import {\n TransactionRejectedRpcError,\n UserRejectedRequestError,\n} from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport { wait } from '../../utils/wait.js'\n\nimport {\n type CreateTransportErrorType,\n type Transport,\n type TransportConfig,\n createTransport,\n} from './createTransport.js'\n// TODO: Narrow `method` & `params` types.\nexport type OnResponseFn = (\n args: {\n method: string\n params: unknown[]\n transport: ReturnType\n } & (\n | {\n error?: undefined\n response: unknown\n status: 'success'\n }\n | {\n error: Error\n response?: undefined\n status: 'error'\n }\n ),\n) => void\n\ntype RankOptions = {\n /**\n * The polling interval (in ms) at which the ranker should ping the RPC URL.\n * @default client.pollingInterval\n */\n interval?: number | undefined\n /**\n * The number of previous samples to perform ranking on.\n * @default 10\n */\n sampleCount?: number | undefined\n /**\n * Timeout when sampling transports.\n * @default 1_000\n */\n timeout?: number | undefined\n /**\n * Weights to apply to the scores. Weight values are proportional.\n */\n weights?:\n | {\n /**\n * The weight to apply to the latency score.\n * @default 0.3\n */\n latency?: number | undefined\n /**\n * The weight to apply to the stability score.\n * @default 0.7\n */\n stability?: number | undefined\n }\n | undefined\n}\n\nexport type FallbackTransportConfig = {\n /** The key of the Fallback transport. */\n key?: TransportConfig['key'] | undefined\n /** The name of the Fallback transport. */\n name?: TransportConfig['name'] | undefined\n /** Toggle to enable ranking, or rank options. */\n rank?: boolean | RankOptions | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n}\n\nexport type FallbackTransport<\n transports extends readonly Transport[] = readonly Transport[],\n> = Transport<\n 'fallback',\n {\n onResponse: (fn: OnResponseFn) => void\n transports: {\n [key in keyof transports]: ReturnType\n }\n }\n>\n\nexport type FallbackTransportErrorType = CreateTransportErrorType | ErrorType\n\nexport function fallback(\n transports_: transports,\n config: FallbackTransportConfig = {},\n): FallbackTransport {\n const {\n key = 'fallback',\n name = 'Fallback',\n rank = false,\n retryCount,\n retryDelay,\n } = config\n return (({ chain, pollingInterval = 4_000, timeout, ...rest }) => {\n let transports = transports_\n\n let onResponse: OnResponseFn = () => {}\n\n const transport = createTransport(\n {\n key,\n name,\n async request({ method, params }) {\n const fetch = async (i = 0): Promise => {\n const transport = transports[i]({\n ...rest,\n chain,\n retryCount: 0,\n timeout,\n })\n try {\n const response = await transport.request({\n method,\n params,\n } as any)\n\n onResponse({\n method,\n params: params as unknown[],\n response,\n transport,\n status: 'success',\n })\n\n return response\n } catch (err) {\n onResponse({\n error: err as Error,\n method,\n params: params as unknown[],\n transport,\n status: 'error',\n })\n\n if (shouldThrow(err as Error)) throw err\n\n // If we've reached the end of the fallbacks, throw the error.\n if (i === transports.length - 1) throw err\n\n // Otherwise, try the next fallback.\n return fetch(i + 1)\n }\n }\n return fetch()\n },\n retryCount,\n retryDelay,\n type: 'fallback',\n },\n {\n onResponse: (fn: OnResponseFn) => (onResponse = fn),\n transports: transports.map((fn) => fn({ chain, retryCount: 0 })),\n },\n )\n\n if (rank) {\n const rankOptions = (typeof rank === 'object' ? rank : {}) as RankOptions\n rankTransports({\n chain,\n interval: rankOptions.interval ?? pollingInterval,\n onTransports: (transports_) => (transports = transports_ as transports),\n sampleCount: rankOptions.sampleCount,\n timeout: rankOptions.timeout,\n transports,\n weights: rankOptions.weights,\n })\n }\n return transport\n }) as FallbackTransport\n}\n\nfunction shouldThrow(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (\n error.code === TransactionRejectedRpcError.code ||\n error.code === UserRejectedRequestError.code ||\n error.code === 5000 // CAIP UserRejectedRequestError\n )\n return true\n }\n return false\n}\n\n/** @internal */\nexport function rankTransports({\n chain,\n interval = 4_000,\n onTransports,\n sampleCount = 10,\n timeout = 1_000,\n transports,\n weights = {},\n}: {\n chain?: Chain | undefined\n interval: RankOptions['interval']\n onTransports: (transports: readonly Transport[]) => void\n sampleCount?: RankOptions['sampleCount'] | undefined\n timeout?: RankOptions['timeout'] | undefined\n transports: readonly Transport[]\n weights?: RankOptions['weights'] | undefined\n}) {\n const { stability: stabilityWeight = 0.7, latency: latencyWeight = 0.3 } =\n weights\n\n type SampleData = { latency: number; success: number }\n type Sample = SampleData[]\n const samples: Sample[] = []\n\n const rankTransports_ = async () => {\n // 1. Take a sample from each Transport.\n const sample: Sample = await Promise.all(\n transports.map(async (transport) => {\n const transport_ = transport({ chain, retryCount: 0, timeout })\n\n const start = Date.now()\n let end: number\n let success: number\n try {\n await transport_.request({ method: 'net_listening' })\n success = 1\n } catch {\n success = 0\n } finally {\n end = Date.now()\n }\n const latency = end - start\n return { latency, success }\n }),\n )\n\n // 2. Store the sample. If we have more than `sampleCount` samples, remove\n // the oldest sample.\n samples.push(sample)\n if (samples.length > sampleCount) samples.shift()\n\n // 3. Calculate the max latency from samples.\n const maxLatency = Math.max(\n ...samples.map((sample) =>\n Math.max(...sample.map(({ latency }) => latency)),\n ),\n )\n\n // 4. Calculate the score for each Transport.\n const scores = transports\n .map((_, i) => {\n const latencies = samples.map((sample) => sample[i].latency)\n const meanLatency =\n latencies.reduce((acc, latency) => acc + latency, 0) /\n latencies.length\n const latencyScore = 1 - meanLatency / maxLatency\n\n const successes = samples.map((sample) => sample[i].success)\n const stabilityScore =\n successes.reduce((acc, success) => acc + success, 0) /\n successes.length\n\n if (stabilityScore === 0) return [0, i]\n return [\n latencyWeight * latencyScore + stabilityWeight * stabilityScore,\n i,\n ]\n })\n .sort((a, b) => b[0] - a[0])\n\n // 5. Sort the Transports by score.\n onTransports(scores.map(([, i]) => transports[i]))\n\n // 6. Wait, and then rank again.\n await wait(interval)\n rankTransports_()\n }\n rankTransports_()\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain,\n>(chain: chain): Prettify, chain>> {\n return {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign, chain>\n}\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const mainnet = /*#__PURE__*/ defineChain({\n id: 1,\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://cloudflare-eth.com'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensRegistry: {\n address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',\n },\n ensUniversalResolver: {\n address: '0xce01f8eee7E479C928F8919abD53E553a36CeF67',\n blockCreated: 19_258_213,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n})\n","import { type ChainId } from '@lifi/types'\nimport { config } from '../config.js'\n\nexport const getRpcUrl = async (chainId: ChainId): Promise => {\n const rpcUrls = await getRpcUrls(chainId)\n return rpcUrls[0]\n}\n\nexport const getRpcUrls = async (chainId: ChainId): Promise => {\n const rpcUrls = (await config.getRPCUrls())[chainId]\n if (!rpcUrls?.length) {\n throw new Error('RPC URL not found')\n }\n return rpcUrls\n}\n","import { ChainId } from '@lifi/types'\nimport type { Client } from 'viem'\nimport { createClient, fallback, http, webSocket } from 'viem'\nimport { mainnet, type Chain } from 'viem/chains'\nimport { config } from '../../config.js'\nimport { getRpcUrls } from '../rpc.js'\n\n// cached providers\nconst publicClients: Record = {}\n\n/**\n * Get an instance of a provider for a specific chain\n * @param chainId - Id of the chain the provider is for\n * @returns The public client for the given chain\n */\nexport const getPublicClient = async (chainId: number): Promise => {\n if (!publicClients[chainId]) {\n const urls = await getRpcUrls(chainId)\n const fallbackTransports = urls.map((url) =>\n url.startsWith('wss')\n ? webSocket(url)\n : http(url, {\n batch: {\n batchSize: 64,\n },\n })\n )\n const _chain = await config.getChainById(chainId)\n const chain: Chain = {\n ..._chain,\n ..._chain.metamask,\n name: _chain.metamask.chainName,\n rpcUrls: {\n default: { http: _chain.metamask.rpcUrls },\n public: { http: _chain.metamask.rpcUrls },\n },\n }\n // Add ENS contracts\n if (chain.id === ChainId.ETH) {\n chain.contracts = {\n ...mainnet.contracts,\n ...chain.contracts,\n }\n }\n publicClients[chainId] = createClient({\n chain: chain,\n transport: fallback(fallbackTransports),\n batch: {\n multicall: true,\n },\n })\n }\n\n if (!publicClients[chainId]) {\n throw new Error(`Unable to configure provider for chain ${chainId}`)\n }\n\n return publicClients[chainId]\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n UrlRequiredError,\n type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n type HttpRpcClientOptions,\n getHttpRpcClient,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n type Transport,\n type TransportConfig,\n createTransport,\n} from './createTransport.js'\n\nexport type HttpTransportConfig = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n }\n>\n\nexport type HttpTransportErrorType =\n | CreateTransportErrorType\n | UrlRequiredErrorType\n | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig = {},\n): HttpTransport {\n const {\n batch,\n fetchOptions,\n key = 'http',\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n } = config\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } =\n typeof batch === 'object' ? batch : {}\n const retryCount = config.retryCount ?? retryCount_\n const timeout = timeout_ ?? config.timeout ?? 10_000\n const url_ = url || chain?.rpcUrls.default.http[0]\n if (!url_) throw new UrlRequiredError()\n\n const rpcClient = getHttpRpcClient(url_, {\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n name,\n async request({ method, params }) {\n const body = { method, params }\n\n const { schedule } = createBatchScheduler({\n id: url_,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize\n },\n fn: (body: RpcRequest[]) =>\n rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n })\n return result\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n },\n {\n fetchOptions,\n url: url_,\n },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n account?: accountOrAddress | Account | Address | undefined\n /** Flags for batch settings. */\n batch?:\n | {\n /** Toggle to enable `eth_call` multicall aggregation. */\n multicall?: boolean | Prettify | undefined\n }\n | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default 4_000\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** A key for the client. */\n key?: string | undefined\n /** A name for the client. */\n name?: string | undefined\n /**\n * Frequency (in ms) for polling enabled actions & events.\n * @default 4_000\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | undefined\n /** The RPC transport */\n transport: transport\n /** The type of client. */\n type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions,\n | 'call'\n | 'createContractEventFilter'\n | 'createEventFilter'\n | 'estimateContractGas'\n | 'estimateGas'\n | 'getBlock'\n | 'getBlockNumber'\n | 'getChainId'\n | 'getContractEvents'\n | 'getEnsText'\n | 'getFilterChanges'\n | 'getGasPrice'\n | 'getLogs'\n | 'getTransaction'\n | 'getTransactionCount'\n | 'getTransactionReceipt'\n | 'prepareTransactionRequest'\n | 'readContract'\n | 'sendRawTransaction'\n | 'simulateContract'\n | 'uninstallFilter'\n | 'watchBlockNumber'\n | 'watchContractEvent'\n> &\n Pick, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client` in actions.\nexport type Client<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n extended extends Extended | undefined = Extended | undefined,\n> = Client_Base &\n (extended extends Extended ? extended : unknown) & {\n extend: <\n const client extends Extended &\n ExactPartial>,\n >(\n fn: (\n client: Client,\n ) => client,\n ) => Client<\n transport,\n chain,\n account,\n rpcSchema,\n Prettify & (extended extends Extended ? extended : unknown)\n >\n }\n\ntype Client_Base<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n /** The Account of the Client. */\n account: account\n /** Flags for batch settings. */\n batch?: ClientConfig['batch'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** A key for the client. */\n key: string\n /** A name for the client. */\n name: string\n /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n pollingInterval: number\n /** Request function wrapped with friendly error handling */\n request: EIP1193RequestFn<\n rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n >\n /** The RPC transport */\n transport: ReturnType['config'] & ReturnType['value']\n /** The type of client. */\n type: string\n /** A unique ID for the client. */\n uid: string\n}\n\ntype Extended = Prettify<\n // disallow redefining base properties\n { [_ in keyof Client_Base]?: undefined } & {\n [key: string]: unknown\n }\n>\n\nexport type MulticallBatchOptions = {\n /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n cacheTime = parameters.pollingInterval ?? 4_000,\n ccipRead,\n key = 'base',\n name = 'Base Client',\n pollingInterval = 4_000,\n type = 'base',\n } = parameters\n\n const chain = parameters.chain\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n }\n\n function extend(base: typeof client) {\n type ExtendFn = (base: typeof client) => unknown\n return (extendFn: ExtendFn) => {\n const extended = extendFn(base) as Extended\n for (const key in client) delete extended[key]\n const combined = { ...base, ...extended }\n return Object.assign(combined, { extend: extend(combined as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema(): rpcSchema {\n return null as any\n}\n","import type { BaseToken, ChainId } from '@lifi/types'\nimport type { Address } from 'viem'\nimport { multicall, readContract } from 'viem/actions'\nimport { isNativeTokenAddress } from '../../utils/utils.js'\nimport { allowanceAbi } from './abi.js'\nimport { getPublicClient } from './publicClient.js'\nimport type {\n TokenAllowance,\n TokenSpender,\n TokenSpenderAllowance,\n} from './types.js'\nimport { getMulticallAddress } from './utils.js'\n\nexport const getAllowance = async (\n chainId: ChainId,\n tokenAddress: string,\n ownerAddress: string,\n spenderAddress: string\n): Promise => {\n const client = await getPublicClient(chainId)\n try {\n const approved = (await readContract(client, {\n address: tokenAddress as Address,\n abi: allowanceAbi,\n functionName: 'allowance',\n args: [ownerAddress, spenderAddress],\n })) as bigint\n return approved\n } catch (e) {\n return 0n\n }\n}\n\nexport const getAllowanceMulticall = async (\n chainId: ChainId,\n tokens: TokenSpender[],\n ownerAddress: string\n): Promise => {\n if (!tokens.length) {\n return []\n }\n const multicallAddress = await getMulticallAddress(chainId)\n if (!multicallAddress) {\n throw new Error(`No multicall address configured for chainId ${chainId}.`)\n }\n\n const client = await getPublicClient(chainId)\n\n const contracts = tokens.map((token) => ({\n address: token.token.address as Address,\n abi: allowanceAbi,\n functionName: 'allowance',\n args: [ownerAddress, token.spenderAddress],\n }))\n\n const results = await multicall(client, {\n contracts,\n multicallAddress: multicallAddress as Address,\n })\n\n if (!results.length) {\n throw new Error(\n `Couldn't load allowance from chainId ${chainId} using multicall.`\n )\n }\n\n return tokens.map(({ token, spenderAddress }, i: number) => ({\n token,\n spenderAddress,\n allowance: results[i].result as bigint,\n }))\n}\n\n/**\n * Get the current allowance for a certain token.\n * @param token - The token that should be checked\n * @param ownerAddress - The owner of the token\n * @param spenderAddress - The spender address that has to be approved\n * @returns Returns allowance\n */\nexport const getTokenAllowance = async (\n token: BaseToken,\n ownerAddress: string,\n spenderAddress: string\n): Promise => {\n // native token don't need approval\n if (isNativeTokenAddress(token.address)) {\n return\n }\n\n const approved = await getAllowance(\n token.chainId,\n token.address,\n ownerAddress,\n spenderAddress\n )\n return approved\n}\n\n/**\n * Get the current allowance for a list of token/spender address pairs.\n * @param ownerAddress - The owner of the tokens\n * @param tokens - A list of token and spender address pairs\n * @returns Returns array of tokens and their allowance\n */\nexport const getTokenAllowanceMulticall = async (\n ownerAddress: string,\n tokens: TokenSpender[]\n): Promise => {\n // filter out native tokens\n const filteredTokens = tokens.filter(\n ({ token }) => !isNativeTokenAddress(token.address)\n )\n\n // group by chain\n const tokenDataByChain: { [chainId: number]: TokenSpender[] } = {}\n filteredTokens.forEach((data) => {\n if (!tokenDataByChain[data.token.chainId]) {\n tokenDataByChain[data.token.chainId] = []\n }\n tokenDataByChain[data.token.chainId].push(data)\n })\n\n const chainKeys = Object.keys(tokenDataByChain).map(Number.parseInt)\n\n const allowances = (\n await Promise.all(\n chainKeys.map(async (chainId) => {\n // get allowances for current chain and token list\n return getAllowanceMulticall(\n chainId,\n tokenDataByChain[chainId],\n ownerAddress\n )\n })\n )\n ).flat()\n\n return allowances\n}\n","import { type LiFiStep, type Process } from '@lifi/types'\nimport { TransactionError, UnknownError } from '../../errors/errors.js'\nimport { SDKError } from '../../errors/SDKError.js'\nimport { ErrorMessage, LiFiErrorCode } from '../../errors/constants.js'\nimport { BaseError } from '../../utils/index.js'\nimport { fetchTxErrorDetails } from '../../helpers.js'\n\nexport const parseEVMErrors = async (\n e: Error,\n step?: LiFiStep,\n process?: Process\n): Promise => {\n if (e instanceof SDKError) {\n e.step = e.step ?? step\n e.process = e.process ?? process\n return e\n }\n\n const baseError = await handleSpecificErrors(e, step, process)\n\n return new SDKError(baseError, step, process)\n}\n\nconst handleSpecificErrors = async (\n e: any,\n step?: LiFiStep,\n process?: Process\n) => {\n if (e.cause?.name === 'UserRejectedRequestError') {\n return new TransactionError(LiFiErrorCode.SignatureRejected, e.message, e)\n }\n\n if (\n step &&\n process?.txHash &&\n e.code === LiFiErrorCode.TransactionFailed &&\n e.message === ErrorMessage.TransactionReverted\n ) {\n const response = await fetchTxErrorDetails(\n process.txHash,\n step.action.fromChainId\n )\n\n const errorMessage = response?.error_message\n\n if (errorMessage?.toLowerCase().includes('out of gas')) {\n return new TransactionError(\n LiFiErrorCode.GasLimitError,\n ErrorMessage.GasLimitLow,\n e\n )\n }\n }\n\n if (e instanceof BaseError) {\n return e\n }\n\n return new UnknownError(e.message || ErrorMessage.UnknownError, e)\n}\n","import { name, version } from './version.js'\nimport { ValidationError } from './errors/errors.js'\nimport { SDKError } from './errors/SDKError.js'\nimport type { Route, LiFiStep } from '@lifi/types'\n\nexport const checkPackageUpdates = async (\n packageName?: string,\n packageVersion?: string\n) => {\n try {\n const pkgName = packageName ?? name\n const response = await fetch(`https://registry.npmjs.org/${pkgName}/latest`)\n const reponseBody = await response.json()\n const latestVersion = reponseBody.version\n const currentVersion = packageVersion ?? version\n\n if (latestVersion > currentVersion) {\n console.warn(\n // eslint-disable-next-line max-len\n `${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`\n )\n }\n } catch (error) {\n // Cannot verify version, might be network error etc. We don't bother showing anything in that case\n }\n}\n\n/**\n * Converts a quote to Route\n * @param step - Step returned from the quote endpoint.\n * @param txHash\n * @param chainId\n * @returns - The route to be executed.\n * @throws {BaseError} Throws a ValidationError if the step has missing values.\n */\nexport const convertQuoteToRoute = (step: LiFiStep): Route => {\n if (!step.estimate.fromAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'fromAmountUSD' in step estimate.\")\n )\n }\n\n if (!step.estimate.toAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'toAmountUSD' in step estimate.\")\n )\n }\n\n const route: Route = {\n fromToken: step.action.fromToken,\n toToken: step.action.toToken,\n fromAmount: step.action.fromAmount,\n toAmount: step.estimate.toAmount,\n id: step.id,\n fromChainId: step.action.fromToken.chainId,\n toChainId: step.action.toToken.chainId,\n fromAmountUSD: step.estimate.fromAmountUSD,\n toAmountUSD: step.estimate.toAmountUSD,\n steps: [step],\n toAmountMin: step.estimate.toAmountMin,\n insurance: { state: 'NOT_INSURABLE', feeAmountUsd: '0' },\n }\n\n return route\n}\n\nexport const fetchTxErrorDetails = async (txHash: string, chainId: number) => {\n try {\n const response = await fetch(\n `https://api.tenderly.co/api/v1/public-contract/${chainId}/tx/${txHash}`\n )\n const reponseBody = await response.json()\n\n return reponseBody\n } catch (_) {}\n}\n","import { type ChainId } from '@lifi/types'\nimport type { Client, Transaction } from 'viem'\nimport { getBlock } from 'viem/actions'\nimport { config } from '../../config.js'\nimport { median } from '../../utils/median.js'\n\nexport const getMaxPriorityFeePerGas = async (\n client: Client\n): Promise => {\n const block = await getBlock(client, {\n includeTransactions: true,\n })\n\n const maxPriorityFeePerGasList = (block.transactions as Transaction[])\n .filter((tx) => tx.maxPriorityFeePerGas)\n .map((tx) => tx.maxPriorityFeePerGas) as bigint[]\n\n if (!maxPriorityFeePerGasList.length) {\n return\n }\n\n const maxPriorityFeePerGasSum = maxPriorityFeePerGasList.reduce(\n (acc, value) => (acc += value),\n 0n\n )\n\n const maxPriorityFeePerGasMedian = median(maxPriorityFeePerGasList) ?? 0n\n\n const maxPriorityFeePerGasAvg =\n maxPriorityFeePerGasSum / BigInt(maxPriorityFeePerGasList.length)\n\n return maxPriorityFeePerGasMedian > maxPriorityFeePerGasAvg\n ? maxPriorityFeePerGasAvg\n : maxPriorityFeePerGasMedian\n}\n\n// Multicall\nexport const getMulticallAddress = async (\n chainId: ChainId\n): Promise => {\n const chains = await config.getChains()\n return chains.find((chain) => chain.id === chainId)?.multicallAddress\n}\n\n// Modified viem retryDelay exponential backoff function.\nexport const retryDelay = ({ count }: { count: number; error: Error }) =>\n Math.min(~~(1 << count) * 200, 3000)\n\nexport const retryCount = 30\n","export const median = (arr: bigint[]): bigint | undefined => {\n if (!arr.length) {\n return\n }\n const s = [...arr].sort((a, b) => (a > b ? 1 : a < b ? -1 : 0))\n const mid = Math.floor(s.length / 2)\n if (s.length % 2 === 0) {\n return (s[mid - 1] + s[mid]) / 2n\n }\n return s[mid]\n}\n","import type { Client, Hash, SendTransactionParameters } from 'viem'\nimport { encodeFunctionData } from 'viem'\nimport { sendTransaction } from 'viem/actions'\nimport { isNativeTokenAddress } from '../../utils/utils.js'\nimport type { ExecutionOptions, TransactionParameters } from '../types.js'\nimport { approveAbi } from './abi.js'\nimport { getAllowance } from './getAllowance.js'\nimport type { ApproveTokenRequest, RevokeApprovalRequest } from './types.js'\nimport { getMaxPriorityFeePerGas } from './utils.js'\n\nexport const setAllowance = async (\n client: Client,\n tokenAddress: string,\n contractAddress: string,\n amount: bigint,\n settings?: ExecutionOptions,\n returnPopulatedTransaction?: boolean\n): Promise => {\n const data = encodeFunctionData({\n abi: approveAbi,\n functionName: 'approve',\n args: [contractAddress, amount],\n })\n\n if (returnPopulatedTransaction) {\n return data\n }\n\n let transactionRequest: TransactionParameters = {\n to: tokenAddress,\n data,\n maxPriorityFeePerGas:\n client.account?.type === 'local'\n ? await getMaxPriorityFeePerGas(client)\n : undefined,\n }\n\n if (settings?.updateTransactionRequestHook) {\n const customizedTransactionRequest: TransactionParameters =\n await settings.updateTransactionRequestHook({\n requestType: 'approve',\n ...transactionRequest,\n })\n\n transactionRequest = {\n ...transactionRequest,\n ...customizedTransactionRequest,\n }\n }\n\n return sendTransaction(client, {\n to: transactionRequest.to,\n account: client.account!,\n data: transactionRequest.data,\n gas: transactionRequest.gas,\n gasPrice: transactionRequest.gasPrice,\n maxFeePerGas: transactionRequest.maxFeePerGas,\n maxPriorityFeePerGas: transactionRequest.maxPriorityFeePerGas,\n chain: null,\n } as SendTransactionParameters)\n}\n\n/**\n * Set approval for a certain token and amount.\n * @param request - The approval request\n * @param request.walletClient - The Viem wallet client used to send the transaction\n * @param request.token - The token for which to set the allowance\n * @param request.spenderAddress - The address of the spender\n * @param request.amount - The amount of tokens to approve\n * @returns Returns Hash or nothing\n */\nexport const setTokenAllowance = async ({\n walletClient,\n token,\n spenderAddress,\n amount,\n}: ApproveTokenRequest): Promise => {\n // native token don't need approval\n if (isNativeTokenAddress(token.address)) {\n return\n }\n const approvedAmount = await getAllowance(\n token.chainId,\n token.address,\n walletClient.account!.address,\n spenderAddress\n )\n\n if (amount > approvedAmount) {\n const approveTx = await setAllowance(\n walletClient,\n token.address,\n spenderAddress,\n amount\n )\n\n return approveTx\n }\n}\n\n/**\n * Revoke approval for a certain token.\n * @param request - The revoke request\n * @param request.walletClient - The Viem wallet client used to send the transaction\n * @param request.token - The token for which to revoke the allowance\n * @param request.spenderAddress - The address of the spender\n * @returns Returns Hash or nothing\n */\nexport const revokeTokenApproval = async ({\n walletClient,\n token,\n spenderAddress,\n}: RevokeApprovalRequest): Promise => {\n // native token don't need approval\n if (isNativeTokenAddress(token.address)) {\n return\n }\n const approvedAmount = await getAllowance(\n token.chainId,\n token.address,\n walletClient.account!.address,\n spenderAddress\n )\n if (approvedAmount > 0) {\n const approveTx = await setAllowance(\n walletClient,\n token.address,\n spenderAddress,\n 0n\n )\n\n return approveTx\n }\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record\n\nexport type ObserveErrorType = ErrorType\n\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map void>()\n\ntype EmitFunction = (\n emit: callbacks,\n) => MaybePromise void)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction,\n) {\n const callbackId = ++callbackCount\n\n const getListeners = () => listenersCache.get(observerId) || []\n\n const unsubscribe = () => {\n const listeners = getListeners()\n listenersCache.set(\n observerId,\n listeners.filter((cb: any) => cb.id !== callbackId),\n )\n }\n\n const unwatch = () => {\n const cleanup = cleanupCache.get(observerId)\n if (getListeners().length === 1 && cleanup) cleanup()\n unsubscribe()\n }\n\n const listeners = getListeners()\n listenersCache.set(observerId, [\n ...listeners,\n { id: callbackId, fns: callbacks },\n ])\n\n if (listeners && listeners.length > 0) return unwatch\n\n const emit: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract]\n }\n\n const cleanup = fn(emit)\n if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n return unwatch\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionNotFoundError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters =\n | {\n /** The block hash */\n blockHash: Hash\n blockNumber?: undefined\n blockTag?: undefined\n hash?: undefined\n /** The index of the transaction on the block. */\n index: number\n }\n | {\n blockHash?: undefined\n /** The block number */\n blockNumber: bigint\n blockTag?: undefined\n hash?: undefined\n /** The index of the transaction on the block. */\n index: number\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /** The block tag. */\n blockTag: blockTag | BlockTag\n hash?: undefined\n /** The index of the transaction on the block. */\n index: number\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n blockTag?: undefined\n /** The hash of the transaction. */\n hash: Hash\n index?: number | undefined\n }\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify>\n\nexport type GetTransactionErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n }: GetTransactionParameters,\n): Promise> {\n const blockTag = blockTag_ || 'latest'\n\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n let transaction: RpcTransaction | null = null\n if (hash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if (blockNumberHex || blockTag) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n }\n\n if (!transaction)\n throw new TransactionNotFoundError({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n })\n\n const format =\n client.chain?.formatters?.transaction?.format || formatTransaction\n return format(transaction)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n Chain,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial,\n) {\n const receipt = {\n ...transactionReceipt,\n blockNumber: transactionReceipt.blockNumber\n ? BigInt(transactionReceipt.blockNumber)\n : null,\n contractAddress: transactionReceipt.contractAddress\n ? transactionReceipt.contractAddress\n : null,\n cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n ? BigInt(transactionReceipt.cumulativeGasUsed)\n : null,\n effectiveGasPrice: transactionReceipt.effectiveGasPrice\n ? BigInt(transactionReceipt.effectiveGasPrice)\n : null,\n gasUsed: transactionReceipt.gasUsed\n ? BigInt(transactionReceipt.gasUsed)\n : null,\n logs: transactionReceipt.logs\n ? transactionReceipt.logs.map((log) => formatLog(log))\n : null,\n to: transactionReceipt.to ? transactionReceipt.to : null,\n transactionIndex: transactionReceipt.transactionIndex\n ? hexToNumber(transactionReceipt.transactionIndex)\n : null,\n status: transactionReceipt.status\n ? receiptStatuses[transactionReceipt.status]\n : null,\n type: transactionReceipt.type\n ? transactionType[\n transactionReceipt.type as keyof typeof transactionType\n ] || transactionReceipt.type\n : null,\n } as TransactionReceipt\n\n if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n logIndex: log.logIndex ? Number(log.logIndex) : null,\n transactionHash: log.transactionHash ? log.transactionHash : null,\n transactionIndex: log.transactionIndex\n ? Number(log.transactionIndex)\n : null,\n ...(eventName ? { args, eventName } : {}),\n } as Log\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionReceiptNotFoundError,\n type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n /** The hash of the transaction. */\n hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt(\n client: Client,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(receipt) as GetTransactionReceiptReturnType\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache(cacheKey: string) {\n const buildCache = (cacheKey: string, cache: Map) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype WithCacheParameters = {\n /** The key to cache the data against. */\n cacheKey: string\n /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n cacheTime?: number | undefined\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache(\n fn: () => Promise,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache(cacheKey)\n\n // If a response exists in the cache, and it's not expired, return it\n // and do not invoke the promise.\n // If the max age is 0, the cache is disabled.\n const response = cache.response.get()\n if (response && cacheTime > 0) {\n const age = new Date().getTime() - response.created.getTime()\n if (age < cacheTime) return response.data\n }\n\n let promise = cache.promise.get()\n if (!promise) {\n promise = fn()\n\n // Store the promise in the cache so that subsequent invocations\n // will wait for the same promise to resolve (deduping).\n cache.promise.set(promise)\n }\n\n try {\n const data = await promise\n\n // Store the response in the cache so that subsequent invocations\n // will return the same response.\n cache.response.set({ created: new Date(), data })\n\n return data\n } finally {\n // Clear the promise cache so that subsequent invocations will\n // invoke the promise again.\n cache.promise.clear()\n }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\nexport function getBlockNumberCache(id: string) {\n return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber(\n client: Client,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { HasTransportType } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n type GetBlockNumberReturnType,\n getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n blockNumber: OnBlockNumberParameter,\n prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type WatchBlockNumberParameters<\n transport extends Transport = Transport,\n> = {\n /** The callback to call when a new block number is received. */\n onBlockNumber: OnBlockNumberFn\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n} & (\n | (HasTransportType extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks\n * - JSON-RPC Methods:\n * - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n * - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n * onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (client.transport.type === 'webSocket') return false\n if (\n client.transport.type === 'fallback' &&\n client.transport.transports[0].config.type === 'webSocket'\n )\n return false\n return true\n })()\n\n let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n const pollBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n pollingInterval,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) =>\n poll(\n async () => {\n try {\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({ cacheTime: 0 })\n\n if (prevBlockNumber) {\n // If the current block number is the same as the previous,\n // we can skip.\n if (blockNumber === prevBlockNumber) return\n\n // If we have missed out on some previous blocks, and the\n // `emitMissed` flag is truthy, let's emit those blocks.\n if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n emit.onBlockNumber(i, prevBlockNumber)\n prevBlockNumber = i\n }\n }\n }\n\n // If the next block number is greater than the previous,\n // it is not in the past, and we can emit the new block number.\n if (!prevBlockNumber || blockNumber > prevBlockNumber) {\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n }\n } catch (err) {\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin,\n interval: pollingInterval,\n },\n ),\n )\n }\n\n const subscribeBlockNumber = () => {\n const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType) =>\n transport.config.type === 'webSocket',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.onError?.(error)\n },\n })\n unsubscribe = unsubscribe_\n if (!active) unsubscribe()\n } catch (err) {\n onError?.(err as Error)\n }\n })()\n return () => unsubscribe()\n })\n }\n\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise) | undefined\n // The interval (in ms).\n interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise,\n { emitOnBegin, initialWaitTime, interval }: PollOptions,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | void = undefined\n if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n const initialWait = (await initialWaitTime?.(data)) ?? interval\n await wait(initialWait)\n\n const poll = async () => {\n if (!active) return\n await fn({ unpoll: unwatch })\n await wait(interval)\n poll()\n }\n\n poll()\n }\n watch()\n\n return unwatch\n}\n","import type { ChainId } from '@lifi/types'\nimport type {\n Chain,\n Client,\n Hash,\n ReplacementReason,\n ReplacementReturnType,\n TransactionReceipt,\n} from 'viem'\nimport { waitForTransactionReceipt as waitForTransactionReceiptInternal } from 'viem/actions'\nimport { LiFiErrorCode, TransactionError } from '../../utils/index.js'\nimport { getPublicClient } from './publicClient.js'\nimport { retryCount, retryDelay } from './utils.js'\n\ninterface WaitForTransactionReceiptProps {\n client: Client\n chainId: ChainId\n txHash: Hash\n onReplaced?: (response: ReplacementReturnType) => void\n}\n\nexport async function waitForTransactionReceipt({\n client,\n chainId,\n txHash,\n onReplaced,\n}: WaitForTransactionReceiptProps): Promise {\n let { transactionReceipt, replacementReason } = await waitForReceipt(\n client,\n txHash,\n onReplaced\n )\n\n if (!transactionReceipt?.status) {\n const publicClient = await getPublicClient(chainId)\n const result = await waitForReceipt(publicClient, txHash, onReplaced)\n transactionReceipt = result.transactionReceipt\n replacementReason = result.replacementReason\n }\n\n if (transactionReceipt?.status === 'reverted') {\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n 'Transaction was reverted.'\n )\n }\n if (replacementReason === 'cancelled') {\n throw new TransactionError(\n LiFiErrorCode.TransactionCanceled,\n 'User canceled transaction.'\n )\n }\n\n return transactionReceipt\n}\n\nasync function waitForReceipt(\n client: Client,\n txHash: Hash,\n onReplaced?: (response: ReplacementReturnType) => void\n): Promise<{\n transactionReceipt?: TransactionReceipt\n replacementReason?: ReplacementReason\n}> {\n let replacementReason: ReplacementReason | undefined\n let transactionReceipt: TransactionReceipt | undefined\n\n try {\n transactionReceipt = await waitForTransactionReceiptInternal(client, {\n hash: txHash,\n onReplaced: (response) => {\n replacementReason = response.reason\n onReplaced?.(response)\n },\n retryCount,\n retryDelay,\n })\n } catch (error) {\n // We can ignore errors from waitForTransactionReceipt as we have a status check fallback\n }\n\n return { transactionReceipt, replacementReason }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n TransactionNotFoundError,\n TransactionReceiptNotFoundError,\n WaitForTransactionReceiptTimeoutError,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n type GetTransactionErrorType,\n type GetTransactionReturnType,\n getTransaction,\n} from './getTransaction.js'\nimport {\n type GetTransactionReceiptErrorType,\n type GetTransactionReceiptReturnType,\n getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n type WatchBlockNumberErrorType,\n watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n * - JSON-RPC Methods:\n * - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n * - If a Transaction has been replaced:\n * - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n * - Checks if one of the Transactions is a replacement\n * - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n * hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n chain extends Chain | undefined,\n>(\n client: Client,\n {\n confirmations = 1,\n hash,\n onReplaced,\n pollingInterval = client.pollingInterval,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n }: WaitForTransactionReceiptParameters,\n): Promise> {\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n let transaction: GetTransactionReturnType | undefined\n let replacedTransaction: GetTransactionReturnType | undefined\n let receipt: GetTransactionReceiptReturnType\n let retrying = false\n\n return new Promise((resolve, reject) => {\n if (timeout)\n setTimeout(\n () => reject(new WaitForTransactionReceiptTimeoutError({ hash })),\n timeout,\n )\n\n const _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n (emit) => {\n const _unwatch = getAction(\n client,\n watchBlockNumber,\n 'watchBlockNumber',\n )({\n emitMissed: true,\n emitOnBegin: true,\n poll: true,\n pollingInterval,\n async onBlockNumber(blockNumber_) {\n const done = (fn: () => void) => {\n _unwatch()\n fn()\n _unobserve()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\n\n try {\n // If we already have a valid receipt, let's check if we have enough\n // confirmations. If we do, then we can resolve.\n if (receipt) {\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt))\n return\n }\n\n // Get the transaction to check if it's been replaced.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined transactions.\n if (!transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\n },\n )\n retrying = false\n }\n\n // Get the receipt to check if it's been processed.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n done(() => emit.resolve(receipt))\n } catch (err) {\n // If the receipt is not found, the transaction will be pending.\n // We need to check if it has potentially been replaced.\n if (\n err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\n\n try {\n replacedTransaction = transaction\n\n // Let's retrieve the transactions from the current block.\n // We need to retry as some RPC Providers may be slow to sync\n // up mined blocks.\n retrying = true\n const block = await withRetry(\n () =>\n getAction(\n client,\n getBlock,\n 'getBlock',\n )({\n blockNumber,\n includeTransactions: true,\n }),\n {\n delay: retryDelay,\n retryCount,\n shouldRetry: ({ error }) =>\n error instanceof BlockNotFoundError,\n },\n )\n retrying = false\n\n const replacementTransaction = (\n block.transactions as {} as Transaction[]\n ).find(\n ({ from, nonce }) =>\n from === replacedTransaction!.from &&\n nonce === replacedTransaction!.nonce,\n )\n\n // If we couldn't find a replacement transaction, continue polling.\n if (!replacementTransaction) return\n\n // If we found a replacement transaction, return it's receipt.\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({\n hash: replacementTransaction.hash,\n })\n\n // Check if we have enough confirmations. If not, continue polling.\n if (\n confirmations > 1 &&\n (!receipt.blockNumber ||\n blockNumber - receipt.blockNumber + 1n < confirmations)\n )\n return\n\n let reason: ReplacementReason = 'replaced'\n if (\n replacementTransaction.to === replacedTransaction.to &&\n replacementTransaction.value === replacedTransaction.value\n ) {\n reason = 'repriced'\n } else if (\n replacementTransaction.from === replacementTransaction.to &&\n replacementTransaction.value === 0n\n ) {\n reason = 'cancelled'\n }\n\n done(() => {\n emit.onReplaced?.({\n reason,\n replacedTransaction: replacedTransaction! as any,\n transaction: replacementTransaction,\n transactionReceipt: receipt,\n })\n emit.resolve(receipt)\n })\n } catch (err_) {\n done(() => emit.reject(err_))\n }\n } else {\n done(() => emit.reject(err))\n }\n }\n },\n })\n },\n )\n })\n}\n","import type { Chain, LiFiStep, Process, ProcessType } from '@lifi/types'\nimport type { Address, Client, Hash } from 'viem'\nimport type { StatusManager } from '../StatusManager.js'\nimport type { ExecutionOptions } from '../types.js'\nimport { getAllowance } from './getAllowance.js'\nimport { parseEVMErrors } from './parseEVMErrors.js'\nimport { setAllowance } from './setAllowance.js'\nimport { waitForTransactionReceipt } from './waitForTransactionReceipt.js'\n\nexport const checkAllowance = async (\n client: Client,\n chain: Chain,\n step: LiFiStep,\n statusManager: StatusManager,\n settings?: ExecutionOptions,\n allowUserInteraction = false,\n shouldBatchTransactions = false\n): Promise => {\n // Ask the user to set an allowance\n let allowanceProcess: Process = statusManager.findOrCreateProcess({\n step,\n type: 'TOKEN_ALLOWANCE',\n chainId: step.action.fromChainId,\n })\n\n // Check allowance\n try {\n if (allowanceProcess.txHash && allowanceProcess.status !== 'DONE') {\n await waitForApprovalTransaction(\n client,\n allowanceProcess.txHash! as Address,\n allowanceProcess.type,\n step,\n chain,\n statusManager\n )\n } else {\n allowanceProcess = statusManager.updateProcess(\n step,\n allowanceProcess.type,\n 'STARTED'\n )\n\n const approved = await getAllowance(\n chain.id,\n step.action.fromToken.address,\n client.account!.address,\n step.estimate.approvalAddress\n )\n\n const fromAmount = BigInt(step.action.fromAmount)\n\n if (fromAmount > approved) {\n if (!allowUserInteraction) {\n return\n }\n\n if (shouldBatchTransactions) {\n const approveTxHash = await setAllowance(\n client,\n step.action.fromToken.address,\n step.estimate.approvalAddress,\n fromAmount,\n settings,\n true\n )\n\n allowanceProcess = statusManager.updateProcess(\n step,\n allowanceProcess.type,\n 'DONE'\n )\n\n return approveTxHash\n }\n\n const approveTxHash = await setAllowance(\n client,\n step.action.fromToken.address,\n step.estimate.approvalAddress,\n fromAmount\n )\n await waitForApprovalTransaction(\n client,\n approveTxHash,\n allowanceProcess.type,\n step,\n chain,\n statusManager\n )\n } else {\n allowanceProcess = statusManager.updateProcess(\n step,\n allowanceProcess.type,\n 'DONE'\n )\n }\n }\n } catch (e: any) {\n const error = await parseEVMErrors(e, step, allowanceProcess)\n allowanceProcess = statusManager.updateProcess(\n step,\n allowanceProcess.type,\n 'FAILED',\n {\n error: {\n message: error.cause.message,\n code: error.code,\n },\n }\n )\n statusManager.updateExecution(step, 'FAILED')\n throw error\n }\n}\n\nconst waitForApprovalTransaction = async (\n client: Client,\n txHash: Hash,\n processType: ProcessType,\n step: LiFiStep,\n chain: Chain,\n statusManager: StatusManager\n) => {\n statusManager.updateProcess(step, processType, 'PENDING', {\n txHash,\n txLink: `${chain.metamask.blockExplorerUrls[0]}tx/${txHash}`,\n })\n\n const transactionReceipt = await waitForTransactionReceipt({\n client: client,\n chainId: chain.id,\n txHash: txHash,\n onReplaced(response) {\n statusManager.updateProcess(step, processType, 'PENDING', {\n txHash: response.transaction.hash,\n txLink: `${chain.metamask.blockExplorerUrls[0]}tx/${response.transaction.hash}`,\n })\n },\n })\n\n const transactionHash = transactionReceipt?.transactionHash || txHash\n statusManager.updateProcess(step, processType, 'DONE', {\n txHash: transactionHash,\n txLink: `${chain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`,\n })\n}\n","import type { ExtendedChain, LiFiStep, ProcessType } from '@lifi/types'\nimport type { Hash } from 'viem'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StatusManager } from '../StatusManager.js'\nimport type { MultisigConfig, MultisigTxDetails } from './types.js'\n\nexport const updateMultisigRouteProcess = async (\n internalTxHash: Hash,\n step: LiFiStep,\n processType: ProcessType,\n fromChain: ExtendedChain,\n statusManager: StatusManager,\n multisig?: MultisigConfig\n) => {\n if (!multisig?.getMultisigTransactionDetails) {\n throw new Error(\n 'getMultisigTransactionDetails is missing in multisig config.'\n )\n }\n\n const updateIntermediateMultisigStatus = () => {\n statusManager.updateProcess(step, processType, 'PENDING')\n }\n\n const multisigStatusResponse: MultisigTxDetails =\n await multisig?.getMultisigTransactionDetails(\n internalTxHash,\n fromChain.id,\n updateIntermediateMultisigStatus\n )\n\n if (multisigStatusResponse.status === 'DONE') {\n statusManager.updateProcess(step, processType, 'PENDING', {\n txHash: multisigStatusResponse.txHash,\n multisigTxHash: undefined,\n txLink: `${fromChain.metamask.blockExplorerUrls[0]}tx/${multisigStatusResponse.txHash}`,\n })\n }\n\n if (multisigStatusResponse.status === 'FAILED') {\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n 'Multisig transaction failed.'\n )\n }\n\n if (multisigStatusResponse.status === 'CANCELLED') {\n throw new TransactionError(\n LiFiErrorCode.SignatureRejected,\n 'Transaction was rejected by user.'\n )\n }\n}\n","import type {\n ExtendedTransactionInfo,\n FullStatusData,\n Process,\n} from '@lifi/types'\nimport type { Client, Hash, SendTransactionParameters } from 'viem'\nimport { getAddresses, sendTransaction } from 'viem/actions'\nimport { config } from '../../config.js'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError, ValidationError } from '../../errors/errors.js'\nimport { getStepTransaction } from '../../services/api.js'\nimport {\n getTransactionFailedMessage,\n isZeroAddress,\n} from '../../utils/index.js'\nimport { BaseStepExecutor } from '../BaseStepExecutor.js'\nimport { checkBalance } from '../checkBalance.js'\nimport { getSubstatusMessage } from '../processMessages.js'\nimport { stepComparison } from '../stepComparison.js'\nimport type {\n LiFiStepExtended,\n StepExecutorOptions,\n TransactionParameters,\n} from '../types.js'\nimport { waitForReceivingTransaction } from '../waitForReceivingTransaction.js'\nimport { checkAllowance } from './checkAllowance.js'\nimport { updateMultisigRouteProcess } from './multisig.js'\nimport { parseEVMErrors } from './parseEVMErrors.js'\nimport { switchChain } from './switchChain.js'\nimport type { MultisigConfig, MultisigTransaction } from './types.js'\nimport { getMaxPriorityFeePerGas } from './utils.js'\nimport { waitForTransactionReceipt } from './waitForTransactionReceipt.js'\n\nexport interface EVMStepExecutorOptions extends StepExecutorOptions {\n client: Client\n multisig?: MultisigConfig\n}\n\nexport class EVMStepExecutor extends BaseStepExecutor {\n private client: Client\n private multisig?: MultisigConfig\n\n constructor(options: EVMStepExecutorOptions) {\n super(options)\n this.client = options.client\n this.multisig = options.multisig\n }\n\n // Ensure that we are using the right chain and wallet when executing transactions.\n checkClient = async (\n step: LiFiStepExtended,\n process?: Process\n ): Promise => {\n const updatedClient = await switchChain(\n this.client,\n this.statusManager,\n step,\n this.allowUserInteraction,\n this.executionOptions?.switchChainHook\n )\n if (updatedClient) {\n this.client = updatedClient\n }\n\n // Prevent execution of the quote by wallet different from the one which requested the quote\n let accountAddress = this.client.account?.address\n if (!accountAddress) {\n const accountAddresses = await getAddresses(this.client)\n accountAddress = accountAddresses?.[0]\n }\n if (accountAddress !== step.action.fromAddress) {\n let processToUpdate = process\n if (!processToUpdate) {\n // We need to create some process if we don't have one so we can show the error\n processToUpdate = this.statusManager.findOrCreateProcess({\n step,\n type: 'TRANSACTION',\n })\n }\n const errorMessage =\n 'The wallet address that requested the quote does not match the wallet address attempting to sign the transaction.'\n this.statusManager.updateProcess(step, processToUpdate.type, 'FAILED', {\n error: {\n code: LiFiErrorCode.WalletChangedDuringExecution,\n message: errorMessage,\n },\n })\n this.statusManager.updateExecution(step, 'FAILED')\n throw await parseEVMErrors(\n new TransactionError(\n LiFiErrorCode.WalletChangedDuringExecution,\n errorMessage\n ),\n step,\n process\n )\n }\n return updatedClient\n }\n\n executeStep = async (step: LiFiStepExtended): Promise => {\n step.execution = this.statusManager.initExecutionObject(step)\n\n // Find if it's bridging and the step is waiting for a transaction on the receiving chain\n const recievingChainProcess = step.execution?.process.find(\n (process) => process.type === 'RECEIVING_CHAIN'\n )\n\n // Make sure that the chain is still correct\n // If the step is waiting for a transaction on the receiving chain, we do not switch the chain\n // All changes are already done from the source chain\n // Return the step\n if (recievingChainProcess?.substatus !== 'WAIT_DESTINATION_TRANSACTION') {\n const updatedClient = await this.checkClient(step)\n if (!updatedClient) {\n return step\n }\n }\n\n const isMultisigClient = !!this.multisig?.isMultisigWalletClient\n const multisigBatchTransactions: MultisigTransaction[] = []\n\n const shouldBatchTransactions =\n this.multisig?.shouldBatchTransactions &&\n !!this.multisig.sendBatchTransaction\n\n const fromChain = await config.getChainById(step.action.fromChainId)\n const toChain = await config.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n const currentProcessType = isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n\n // STEP 1: Check allowance\n const existingProcess = step.execution.process.find(\n (p) => p.type === currentProcessType\n )\n\n // Check token approval only if fromToken is not the native token => no approval needed in that case\n const checkForAllowance =\n !existingProcess?.txHash &&\n !isZeroAddress(step.action.fromToken.address) &&\n (shouldBatchTransactions || !isMultisigClient)\n\n if (checkForAllowance) {\n const data = await checkAllowance(\n this.client,\n fromChain,\n step,\n this.statusManager,\n this.executionOptions,\n this.allowUserInteraction,\n shouldBatchTransactions\n )\n\n if (data) {\n // allowance doesn't need value\n const baseTransaction: MultisigTransaction = {\n to: step.action.fromToken.address,\n data,\n }\n\n multisigBatchTransactions.push(baseTransaction)\n }\n }\n\n // STEP 2: Get transaction\n let process = this.statusManager.findOrCreateProcess({\n step,\n type: currentProcessType,\n chainId: fromChain.id,\n })\n\n if (process.status !== 'DONE') {\n const multisigProcess = step.execution.process.find(\n (p) => !!p.multisigTxHash\n )\n\n try {\n if (isMultisigClient && multisigProcess) {\n const multisigTxHash = multisigProcess.multisigTxHash as Hash\n if (!multisigTxHash) {\n throw new ValidationError(\n 'Multisig internal transaction hash is undefined.'\n )\n }\n await updateMultisigRouteProcess(\n multisigTxHash,\n step,\n process.type,\n fromChain,\n this.statusManager,\n this.multisig\n )\n }\n\n let txHash: Hash\n if (process.txHash) {\n // Make sure that the chain is still correct\n const updatedClient = await this.checkClient(step, process)\n if (!updatedClient) {\n return step\n }\n\n // Wait for exiting transaction\n txHash = process.txHash as Hash\n } else {\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'STARTED'\n )\n\n // Check balance\n await checkBalance(this.client.account!.address, step)\n\n // Create new transaction\n if (!step.transactionRequest) {\n const { execution, ...stepBase } = step\n const updatedStep = await getStepTransaction(stepBase)\n const comparedStep = await stepComparison(\n this.statusManager,\n step,\n updatedStep,\n this.allowUserInteraction,\n this.executionOptions\n )\n step = {\n ...comparedStep,\n execution: step.execution,\n }\n }\n\n if (!step.transactionRequest) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction.'\n )\n }\n\n // STEP 3: Send the transaction\n // Make sure that the chain is still correct\n const updatedClient = await this.checkClient(step, process)\n if (!updatedClient) {\n return step\n }\n\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'ACTION_REQUIRED'\n )\n\n if (!this.allowUserInteraction) {\n return step\n }\n\n let transactionRequest: TransactionParameters = {\n to: step.transactionRequest.to,\n from: step.transactionRequest.from,\n data: step.transactionRequest.data,\n value: step.transactionRequest.value\n ? BigInt(step.transactionRequest.value)\n : undefined,\n gas: step.transactionRequest.gasLimit\n ? BigInt(step.transactionRequest.gasLimit)\n : undefined,\n // gasPrice: step.transactionRequest.gasPrice\n // ? BigInt(step.transactionRequest.gasPrice as string)\n // : undefined,\n // maxFeePerGas: step.transactionRequest.maxFeePerGas\n // ? BigInt(step.transactionRequest.maxFeePerGas as string)\n // : undefined,\n maxPriorityFeePerGas:\n this.client.account?.type === 'local'\n ? await getMaxPriorityFeePerGas(this.client)\n : step.transactionRequest.maxPriorityFeePerGas\n ? BigInt(step.transactionRequest.maxPriorityFeePerGas)\n : undefined,\n }\n\n if (this.executionOptions?.updateTransactionRequestHook) {\n const customizedTransactionRequest: TransactionParameters =\n await this.executionOptions.updateTransactionRequestHook({\n requestType: 'transaction',\n ...transactionRequest,\n })\n\n transactionRequest = {\n ...transactionRequest,\n ...customizedTransactionRequest,\n }\n }\n\n if (shouldBatchTransactions && this.multisig?.sendBatchTransaction) {\n if (transactionRequest.to && transactionRequest.data) {\n const populatedTransaction: MultisigTransaction = {\n value: transactionRequest.value,\n to: transactionRequest.to,\n data: transactionRequest.data,\n }\n multisigBatchTransactions.push(populatedTransaction)\n\n txHash = await this.multisig?.sendBatchTransaction(\n multisigBatchTransactions\n )\n } else {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction.'\n )\n }\n } else {\n txHash = await sendTransaction(this.client, {\n to: transactionRequest.to,\n account: this.client.account!,\n data: transactionRequest.data,\n value: transactionRequest.value,\n gas: transactionRequest.gas,\n gasPrice: transactionRequest.gasPrice,\n maxFeePerGas: transactionRequest.maxFeePerGas,\n maxPriorityFeePerGas: transactionRequest.maxPriorityFeePerGas,\n chain: null,\n } as SendTransactionParameters)\n }\n\n // STEP 4: Wait for the transaction\n if (isMultisigClient) {\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'ACTION_REQUIRED',\n {\n multisigTxHash: txHash,\n }\n )\n } else {\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'PENDING',\n {\n txHash: txHash,\n txLink: `${fromChain.metamask.blockExplorerUrls[0]}tx/${txHash}`,\n }\n )\n }\n }\n\n const transactionReceipt = await waitForTransactionReceipt({\n client: this.client,\n chainId: fromChain.id,\n txHash,\n onReplaced: (response) => {\n this.statusManager.updateProcess(step, process.type, 'PENDING', {\n txHash: response.transaction.hash,\n txLink: `${fromChain.metamask.blockExplorerUrls[0]}tx/${response.transaction.hash}`,\n })\n },\n })\n\n // if it's multisig wallet client and the process is in ACTION_REQUIRED\n // then signatures are still needed\n if (isMultisigClient && process.status === 'ACTION_REQUIRED') {\n await updateMultisigRouteProcess(\n transactionReceipt?.transactionHash || txHash,\n step,\n process.type,\n fromChain,\n this.statusManager,\n this.multisig\n )\n }\n\n // Update pending process if the transaction hash from the receipt is different.\n // This might happen if the transaction was replaced.\n if (\n !isMultisigClient &&\n transactionReceipt?.transactionHash &&\n transactionReceipt.transactionHash !== txHash\n ) {\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'PENDING',\n {\n txHash: transactionReceipt.transactionHash,\n txLink: `${fromChain.metamask.blockExplorerUrls[0]}tx/${transactionReceipt.transactionHash}`,\n }\n )\n }\n\n if (isBridgeExecution) {\n process = this.statusManager.updateProcess(step, process.type, 'DONE')\n }\n } catch (e: any) {\n const error = await parseEVMErrors(e, step, process)\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'FAILED',\n {\n error: {\n message: error.cause.message,\n code: error.code,\n },\n }\n )\n this.statusManager.updateExecution(step, 'FAILED')\n\n throw error\n }\n }\n\n // STEP 5: Wait for the receiving chain\n const processTxHash = process.txHash\n if (isBridgeExecution) {\n process = this.statusManager.findOrCreateProcess({\n step,\n type: 'RECEIVING_CHAIN',\n status: 'PENDING',\n chainId: toChain.id,\n })\n }\n let statusResponse: FullStatusData\n\n try {\n if (!processTxHash) {\n throw new Error('Transaction hash is undefined.')\n }\n statusResponse = (await waitForReceivingTransaction(\n processTxHash,\n this.statusManager,\n process.type,\n step\n )) as FullStatusData\n\n const statusReceiving =\n statusResponse.receiving as ExtendedTransactionInfo\n\n process = this.statusManager.updateProcess(step, process.type, 'DONE', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(statusResponse.status, statusResponse.substatus),\n txHash: statusReceiving?.txHash,\n txLink: `${toChain.metamask.blockExplorerUrls[0]}tx/${statusReceiving?.txHash}`,\n })\n\n this.statusManager.updateExecution(step, 'DONE', {\n fromAmount: statusResponse.sending.amount,\n toAmount: statusReceiving?.amount,\n toToken: statusReceiving?.token,\n gasCosts: [\n {\n amount: statusResponse.sending.gasAmount,\n amountUSD: statusResponse.sending.gasAmountUSD,\n token: statusResponse.sending.gasToken,\n estimate: statusResponse.sending.gasUsed,\n limit: statusResponse.sending.gasUsed,\n price: statusResponse.sending.gasPrice,\n type: 'SEND',\n },\n ],\n })\n } catch (e: unknown) {\n const htmlMessage = await getTransactionFailedMessage(\n step,\n process.txLink\n )\n\n process = this.statusManager.updateProcess(step, process.type, 'FAILED', {\n error: {\n code: LiFiErrorCode.TransactionFailed,\n message: 'Failed while waiting for receiving chain.',\n htmlMessage,\n },\n })\n this.statusManager.updateExecution(step, 'FAILED')\n throw await parseEVMErrors(e as Error, step, process)\n }\n\n // DONE\n return step\n }\n}\n","import type { Client } from 'viem'\nimport { getChainId } from 'viem/actions'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { ProviderError } from '../../errors/errors.js'\nimport type { StatusManager } from '../StatusManager.js'\nimport type { LiFiStepExtended, SwitchChainHook } from '../types.js'\n\n/**\n * This method checks whether the wallet client is configured for the correct chain.\n * If yes it returns the wallet clien.\n * If no and if user interaction is allowed it triggers the switchChainHook. If no user interaction is allowed it aborts.\n *\n * Account Type: local -\n * We need to create and return a new connector client from the switchChainHook in order to continue execution on a new chain.\n *\n * Account Type: json-rpc -\n * We can switch chain and return existing connector client from the switchChainHook in order to continue execution on a new chain.\n * @param client\n * @param statusManager\n * @param step\n * @param switchChainHook\n * @param allowUserInteraction\n * @returns New connector client\n */\nexport const switchChain = async (\n client: Client,\n statusManager: StatusManager,\n step: LiFiStepExtended,\n allowUserInteraction: boolean,\n switchChainHook?: SwitchChainHook\n): Promise => {\n // if we are already on the correct chain we can proceed directly\n const currentChainId = await getChainId(client)\n if (currentChainId === step.action.fromChainId) {\n return client\n }\n\n // -> set status message\n step.execution = statusManager.initExecutionObject(step)\n statusManager.updateExecution(step, 'ACTION_REQUIRED')\n\n let switchProcess = statusManager.findOrCreateProcess({\n step,\n type: 'SWITCH_CHAIN',\n status: 'ACTION_REQUIRED',\n })\n\n if (!allowUserInteraction) {\n return\n }\n\n try {\n const updatedClient = await switchChainHook?.(step.action.fromChainId)\n let updatedChainId\n if (updatedClient) {\n updatedChainId = await getChainId(updatedClient)\n }\n if (updatedChainId !== step.action.fromChainId) {\n throw new ProviderError(\n LiFiErrorCode.ChainSwitchError,\n 'Chain switch required.'\n )\n }\n\n switchProcess = statusManager.updateProcess(\n step,\n switchProcess.type,\n 'DONE'\n )\n statusManager.updateExecution(step, 'PENDING')\n return updatedClient\n } catch (error: any) {\n statusManager.updateProcess(step, switchProcess.type, 'FAILED', {\n error: {\n message: error.message,\n code: LiFiErrorCode.ChainSwitchError,\n },\n })\n statusManager.updateExecution(step, 'FAILED')\n throw error\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetAddressesReturnType = Address[]\n\nexport type GetAddressesErrorType =\n | RequestErrorType\n | ChecksumAddressErrorType\n | ErrorType\n\n/**\n * Returns a list of account addresses owned by the wallet or client.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getAddresses\n * - JSON-RPC Methods: [`eth_accounts`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_accounts)\n *\n * @param client - Client to use\n * @returns List of account addresses owned by the wallet or client. {@link GetAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getAddresses } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const accounts = await getAddresses(client)\n */\nexport async function getAddresses<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client): Promise {\n if (client.account?.type === 'local') return [client.account.address]\n const addresses = await client.request(\n { method: 'eth_accounts' },\n { dedupe: true },\n )\n return addresses.map((address) => checksumAddress(address))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n if (label.length !== 66) return null\n if (label.indexOf('[') !== 0) return null\n if (label.indexOf(']') !== 65) return null\n const hash = `0x${label.slice(1, 65)}`\n if (!isHex(hash)) return null\n return hash\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n type StringToBytesErrorType,\n type ToBytesErrorType,\n stringToBytes,\n toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | ToBytesErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ConcatErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0xf246651c1b9a6b141d19c2604e9a58f567973833990f830d882534a747801359'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n let result = new Uint8Array(32).fill(0)\n if (!name) return bytesToHex(result)\n\n const labels = name.split('.')\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n const hashed = hashFromEncodedLabel\n ? toBytes(hashFromEncodedLabel)\n : keccak256(stringToBytes(labels[i]), 'bytes')\n result = keccak256(concat([result, hashed]), 'bytes')\n }\n\n return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type EncodedLabelToLabelhashErrorType,\n encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n | BytesToHexErrorType\n | EncodedLabelToLabelhashErrorType\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n const result = new Uint8Array(32).fill(0)\n if (!label) return bytesToHex(result)\n return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n type StringToBytesErrorType,\n stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n type EncodeLabelhashErrorType,\n encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n | EncodeLabelhashErrorType\n | LabelhashErrorType\n | StringToBytesErrorType\n | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n *\n * @example\n * packetToBytes('awkweb.eth')\n * '0x0661776b7765620365746800'\n *\n * @see https://docs.ens.domains/resolution/names#dns\n *\n */\nexport function packetToBytes(packet: string): ByteArray {\n // strip leading and trailing `.`\n const value = packet.replace(/^\\.|\\.$/gm, '')\n if (value.length === 0) return new Uint8Array(1)\n\n const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n let offset = 0\n const list = value.split('.')\n for (let i = 0; i < list.length; i++) {\n let encoded = stringToBytes(list[i])\n // if the length is > 255, make the encoded label value a labelhash\n // this is compatible with the universal resolver\n if (encoded.byteLength > 255)\n encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n bytes[offset] = encoded.length\n bytes.set(encoded, offset + 1)\n offset += encoded.length + 1\n }\n\n if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n return bytes\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n addressResolverAbi,\n universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n type PacketToBytesErrorType,\n packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type ReadContractParameters,\n readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n Pick & {\n /** ENSIP-9 compliant coinType used to resolve addresses for other chains */\n coinType?: number | undefined\n /** Universal Resolver gateway URLs to use for resolving CCIP-read requests. */\n gatewayUrls?: string[] | undefined\n /** Name to get the address for. */\n name: string\n /** Whether or not to throw errors propagated from the ENS Universal Resolver Contract. */\n strict?: boolean | undefined\n /** Address of ENS Universal Resolver Contract. */\n universalResolverAddress?: Address | undefined\n }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n | GetChainContractAddressErrorType\n | EncodeFunctionDataErrorType\n | NamehashErrorType\n | ToHexErrorType\n | PacketToBytesErrorType\n | DecodeFunctionResultErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n * name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress(\n client: Client,\n {\n blockNumber,\n blockTag,\n coinType,\n name,\n gatewayUrls,\n strict,\n universalResolverAddress: universalResolverAddress_,\n }: GetEnsAddressParameters,\n): Promise {\n let universalResolverAddress = universalResolverAddress_\n if (!universalResolverAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. universalResolverAddress is required.',\n )\n\n universalResolverAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'ensUniversalResolver',\n })\n }\n\n try {\n const functionData = encodeFunctionData({\n abi: addressResolverAbi,\n functionName: 'addr',\n ...(coinType != null\n ? { args: [namehash(name), BigInt(coinType)] }\n : { args: [namehash(name)] }),\n })\n\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverResolveAbi,\n functionName: 'resolve',\n args: [toHex(packetToBytes(name)), functionData],\n blockNumber,\n blockTag,\n } as const\n\n const readContractAction = getAction(client, readContract, 'readContract')\n\n const res = gatewayUrls\n ? await readContractAction({\n ...readContractParameters,\n args: [...readContractParameters.args, gatewayUrls],\n })\n : await readContractAction(readContractParameters)\n\n if (res[0] === '0x') return null\n\n const address = decodeFunctionResult({\n abi: addressResolverAbi,\n args: coinType != null ? [namehash(name), BigInt(coinType)] : undefined,\n functionName: 'addr',\n data: res[0],\n })\n\n if (address === '0x') return null\n if (trim(address) === '0x00') return null\n return address\n } catch (err) {\n if (strict) throw err\n if (isNullUniversalResolverError(err, 'resolve')) return null\n throw err\n }\n}\n","import { panicReasons } from '../../constants/solidity.js'\nimport { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(\n err: unknown,\n callType: 'resolve' | 'reverse',\n): boolean {\n if (!(err instanceof BaseError)) return false\n const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (!(cause instanceof ContractFunctionRevertedError)) return false\n if (cause.data?.errorName === 'ResolverNotFound') return true\n if (cause.data?.errorName === 'ResolverWildcardNotSupported') return true\n if (cause.data?.errorName === 'ResolverNotContract') return true\n if (cause.data?.errorName === 'ResolverError') return true\n if (cause.data?.errorName === 'HttpError') return true\n // Backwards compatibility for older UniversalResolver contracts\n if (\n cause.reason?.includes(\n 'Wildcard on non-extended resolvers is not supported',\n )\n )\n return true\n // No primary name set for address.\n if (callType === 'reverse' && cause.reason === panicReasons[50]) return true\n return false\n}\n","import { ens_normalize } from '@adraffy/ens-normalize'\nimport type { ErrorType } from '../../errors/utils.js'\n\nexport type NormalizeErrorType = ErrorType\n\n/**\n * @description Normalizes ENS name according to ENSIP-15.\n *\n * @example\n * normalize('wevm.eth')\n * 'wevm.eth'\n *\n * @see https://docs.ens.domains/contract-api-reference/name-processing#normalising-names\n * @see https://github.com/ensdomains/docs/blob/9edf9443de4333a0ea7ec658a870672d5d180d53/ens-improvement-proposals/ensip-15-normalization-standard.md\n */\nexport function normalize(name: string) {\n return ens_normalize(name)\n}\n","import { ChainId } from '@lifi/types'\nimport { getEnsAddress, normalize } from 'viem/ens'\nimport { getPublicClient } from './publicClient.js'\n\nexport const getENSAddress = async (\n name: string\n): Promise => {\n try {\n const client = await getPublicClient(ChainId.ETH)\n const address = await getEnsAddress(client, {\n name: normalize(name),\n })\n return address as string | undefined\n } catch (_) {\n // ignore\n return\n }\n}\n","import type { ChainId, Token, TokenAmount } from '@lifi/types'\nimport type { Address } from 'viem'\nimport {\n getBalance,\n getBlockNumber,\n multicall,\n readContract,\n} from 'viem/actions'\nimport { isZeroAddress } from '../../utils/utils.js'\nimport { balanceOfAbi, getEthBalanceAbi } from './abi.js'\nimport { getPublicClient } from './publicClient.js'\nimport { getMulticallAddress } from './utils.js'\n\nexport const getEVMBalance = async (\n walletAddress: string,\n tokens: Token[]\n): Promise => {\n if (tokens.length === 0) {\n return []\n }\n const { chainId } = tokens[0]\n tokens.forEach((token) => {\n if (token.chainId !== chainId) {\n console.warn(`Requested tokens have to be on the same chain.`)\n }\n })\n\n const multicallAddress = await getMulticallAddress(chainId)\n\n if (multicallAddress && tokens.length > 1) {\n return getEVMBalanceMulticall(\n chainId,\n tokens,\n walletAddress,\n multicallAddress\n )\n } else {\n return getEVMBalanceDefault(chainId, tokens, walletAddress)\n }\n}\n\nconst getEVMBalanceMulticall = async (\n chainId: ChainId,\n tokens: Token[],\n walletAddress: string,\n multicallAddress: string\n): Promise => {\n const client = await getPublicClient(chainId)\n\n const contracts = tokens.map((token) => {\n if (isZeroAddress(token.address)) {\n return {\n address: multicallAddress as Address,\n abi: getEthBalanceAbi,\n functionName: 'getEthBalance',\n args: [walletAddress],\n }\n }\n return {\n address: token.address as Address,\n abi: balanceOfAbi,\n functionName: 'balanceOf',\n args: [walletAddress],\n }\n })\n const blockNumber = await getBlockNumber(client)\n const results = await multicall(client, {\n contracts,\n multicallAddress: multicallAddress as Address,\n blockNumber,\n })\n\n if (!results.length) {\n return []\n }\n\n return tokens.map((token, i: number) => {\n return {\n ...token,\n amount: results[i].result as bigint,\n blockNumber,\n }\n })\n}\n\nconst getEVMBalanceDefault = async (\n chainId: ChainId,\n tokens: Token[],\n walletAddress: string\n): Promise => {\n const client = await getPublicClient(chainId)\n const blockNumber = await getBlockNumber(client)\n const queue: Promise[] = tokens.map((token) => {\n if (isZeroAddress(token.address)) {\n return getBalance(client, {\n address: walletAddress as Address,\n })\n }\n return readContract(client, {\n address: token.address as Address,\n abi: balanceOfAbi,\n functionName: 'balanceOf',\n args: [walletAddress],\n }) as Promise\n })\n\n const results = await Promise.allSettled(queue)\n\n const tokenAmounts: TokenAmount[] = tokens.map((token, index) => {\n const result = results[index]\n if (result.status === 'rejected') {\n return {\n ...token,\n blockNumber,\n }\n }\n return {\n ...token,\n amount: result.value,\n blockNumber,\n }\n })\n return tokenAmounts\n}\n","import type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record\n } = {},\n> = Pick & {\n allowFailure?: allowFailure | boolean | undefined\n batchSize?: number | undefined\n contracts: MulticallContracts<\n Narrow,\n { mutability: AbiStateMutability } & options\n >\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client,\n parameters: MulticallParameters,\n): Promise> {\n const {\n allowFailure = true,\n batchSize: batchSize_,\n blockNumber,\n blockTag,\n multicallAddress: multicallAddress_,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const batchSize =\n batchSize_ ??\n ((typeof client.batch?.multicall === 'object' &&\n client.batch.multicall.batchSize) ||\n 1_024)\n\n let multicallAddress = multicallAddress_\n if (!multicallAddress) {\n if (!client.chain)\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n\n multicallAddress = getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n abi: multicall3Abi,\n address: multicallAddress!,\n args: [calls],\n blockNumber,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType\n}\n","import { ChainId } from '@lifi/types'\nimport { Connection } from '@solana/web3.js'\nimport { getRpcUrl } from '../rpc.js'\n\nlet connection: Connection | undefined = undefined\n\n/**\n * getSolanaConnection is just a thin wrapper around getting the connection (RPC provider) for Solana\n * @returns - Solana RPC connection\n */\nexport const getSolanaConnection = async (): Promise => {\n if (!connection) {\n const rpcUrl = await getRpcUrl(ChainId.SOL)\n connection = new Connection(rpcUrl)\n return connection\n } else {\n return connection\n }\n}\n","import type { LiFiStep, Process } from '@lifi/types'\nimport { BaseError } from '../../errors/baseError.js'\nimport { ErrorMessage, LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError, UnknownError } from '../../errors/errors.js'\nimport { SDKError } from '../../errors/SDKError.js'\n\nexport const parseSolanaErrors = async (\n e: Error,\n step?: LiFiStep,\n process?: Process\n): Promise => {\n if (e instanceof SDKError) {\n e.step = e.step ?? step\n e.process = e.process ?? process\n return e\n }\n\n const baseError = handleSpecificErrors(e)\n\n return new SDKError(baseError, step, process)\n}\n\nconst handleSpecificErrors = (e: any) => {\n if (e.name === 'WalletSignTransactionError') {\n return new TransactionError(LiFiErrorCode.SignatureRejected, e.message, e)\n }\n\n if (e.name === 'SendTransactionError') {\n return new TransactionError(LiFiErrorCode.TransactionFailed, e.message, e)\n }\n\n if (e.name === 'TransactionExpiredBlockheightExceededError') {\n return new TransactionError(LiFiErrorCode.TransactionExpired, e.message, e)\n }\n\n if (e.message?.includes('simulate')) {\n return new TransactionError(\n LiFiErrorCode.TransactionSimulationFailed,\n e.message,\n e\n )\n }\n\n if (e instanceof BaseError) {\n return e\n }\n\n return new UnknownError(e.message || ErrorMessage.UnknownError, e)\n}\n","import type { ExtendedTransactionInfo, FullStatusData } from '@lifi/types'\nimport { type SignerWalletAdapter } from '@solana/wallet-adapter-base'\nimport {\n VersionedTransaction,\n type SendOptions,\n type SignatureResult,\n} from '@solana/web3.js'\nimport bs58 from 'bs58'\nimport { config } from '../../config.js'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport { getStepTransaction } from '../../services/api.js'\nimport { base64ToUint8Array } from '../../utils/base64ToUint8Array.js'\nimport { getTransactionFailedMessage } from '../../utils/index.js'\nimport { BaseStepExecutor } from '../BaseStepExecutor.js'\nimport { checkBalance } from '../checkBalance.js'\nimport { getSubstatusMessage } from '../processMessages.js'\nimport { stepComparison } from '../stepComparison.js'\nimport type {\n LiFiStepExtended,\n StepExecutorOptions,\n TransactionParameters,\n} from '../types.js'\nimport { sleep } from '../utils.js'\nimport { waitForReceivingTransaction } from '../waitForReceivingTransaction.js'\nimport { getSolanaConnection } from './connection.js'\nimport { parseSolanaErrors } from './parseSolanaErrors.js'\n\nexport interface SolanaStepExecutorOptions extends StepExecutorOptions {\n walletAdapter: SignerWalletAdapter\n}\n\nexport class SolanaStepExecutor extends BaseStepExecutor {\n private walletAdapter: SignerWalletAdapter\n\n constructor(options: SolanaStepExecutorOptions) {\n super(options)\n this.walletAdapter = options.walletAdapter\n }\n\n checkWalletAdapter = (step: LiFiStepExtended) => {\n // Prevent execution of the quote by wallet different from the one which requested the quote\n if (this.walletAdapter.publicKey!.toString() !== step.action.fromAddress) {\n throw new TransactionError(\n LiFiErrorCode.WalletChangedDuringExecution,\n 'The wallet address that requested the quote does not match the wallet address attempting to sign the transaction.'\n )\n }\n }\n\n executeStep = async (step: LiFiStepExtended): Promise => {\n step.execution = this.statusManager.initExecutionObject(step)\n\n const fromChain = await config.getChainById(step.action.fromChainId)\n const toChain = await config.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n const currentProcessType = isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n\n // STEP 2: Get transaction\n let process = this.statusManager.findOrCreateProcess({\n step,\n type: currentProcessType,\n })\n\n if (process.status !== 'DONE') {\n try {\n const connection = await getSolanaConnection()\n\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'STARTED'\n )\n\n // Check balance\n await checkBalance(this.walletAdapter.publicKey!.toString(), step)\n\n // Create new transaction\n if (!step.transactionRequest) {\n const { execution, ...stepBase } = step\n const updatedStep = await getStepTransaction(stepBase)\n const comparedStep = await stepComparison(\n this.statusManager,\n step,\n updatedStep,\n this.allowUserInteraction,\n this.executionOptions\n )\n step = {\n ...comparedStep,\n execution: step.execution,\n }\n }\n\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction.'\n )\n }\n\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'ACTION_REQUIRED'\n )\n\n if (!this.allowUserInteraction) {\n return step\n }\n\n let transactionRequest: TransactionParameters = {\n data: step.transactionRequest.data,\n }\n\n const blockhashResult = await connection.getLatestBlockhash({\n commitment: 'confirmed',\n })\n\n if (this.executionOptions?.updateTransactionRequestHook) {\n const customizedTransactionRequest: TransactionParameters =\n await this.executionOptions.updateTransactionRequestHook({\n requestType: 'transaction',\n ...transactionRequest,\n })\n\n transactionRequest = {\n ...transactionRequest,\n ...customizedTransactionRequest,\n }\n }\n\n if (!transactionRequest.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction.'\n )\n }\n\n const versionedTransaction = VersionedTransaction.deserialize(\n base64ToUint8Array(transactionRequest.data)\n )\n\n this.checkWalletAdapter(step)\n\n const signedTxPromise =\n this.walletAdapter.signTransaction(versionedTransaction)\n\n // We give users 2 minutes to sign the transaction or it should be considered expired\n const signedTx = await Promise.race([\n signedTxPromise,\n // https://solana.com/docs/advanced/confirmation#transaction-expiration\n // Use 2 minutes to account for fluctuations\n sleep(120_000),\n ])\n\n if (!signedTx) {\n throw new TransactionError(\n LiFiErrorCode.TransactionExpired,\n 'Transaction has expired: blockhash is no longer recent enough.'\n )\n }\n\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'PENDING'\n )\n\n const simulationResult = await connection.simulateTransaction(\n signedTx,\n {\n commitment: 'processed',\n replaceRecentBlockhash: true,\n }\n )\n\n if (simulationResult.value.err) {\n throw new TransactionError(\n LiFiErrorCode.TransactionSimulationFailed,\n 'Transaction simulation failed'\n )\n }\n\n // Create transaction hash (signature)\n const txSignature = bs58.encode(signedTx.signatures[0])\n\n // A known weirdness - MAX_RECENT_BLOCKHASHES is 300\n // https://github.com/solana-labs/solana/blob/master/sdk/program/src/clock.rs#L123\n // but MAX_PROCESSING_AGE is 150\n // https://github.com/solana-labs/solana/blob/master/sdk/program/src/clock.rs#L129\n // the blockhash queue in the bank tells you 300 + current slot, but it won't be accepted 150 blocks later.\n // https://solana.com/docs/advanced/confirmation#transaction-expiration\n const lastValidBlockHeight = blockhashResult.lastValidBlockHeight - 150\n\n // In the following section, we wait and constantly check for the transaction to be confirmed\n // and resend the transaction if it is not confirmed within a certain time interval\n // thus handling tx retries on the client side rather than relying on the RPC\n const abortController = new AbortController()\n const confirmTransactionPromise = connection\n .confirmTransaction(\n {\n signature: txSignature,\n blockhash: blockhashResult.blockhash,\n lastValidBlockHeight: lastValidBlockHeight,\n abortSignal: abortController.signal,\n },\n 'confirmed'\n )\n .then((result) => result.value)\n\n let confirmedTx: SignatureResult | null = null\n let blockHeight = await connection.getBlockHeight()\n\n const rawTransactionOptions: SendOptions = {\n // We can skip preflight check after the first transaction has been sent\n // https://solana.com/docs/advanced/retry#the-cost-of-skipping-preflight\n skipPreflight: true,\n // Setting max retries to 0 as we are handling retries manually\n maxRetries: 0,\n // https://solana.com/docs/advanced/confirmation#use-an-appropriate-preflight-commitment-level\n preflightCommitment: 'confirmed',\n }\n\n const signedTxSerialized = signedTx.serialize()\n\n // https://solana.com/docs/advanced/retry#customizing-rebroadcast-logic\n while (!confirmedTx && blockHeight < lastValidBlockHeight) {\n await connection.sendRawTransaction(\n signedTxSerialized,\n rawTransactionOptions\n )\n confirmedTx = await Promise.race([\n confirmTransactionPromise,\n sleep(1000),\n ])\n if (confirmedTx) {\n break\n }\n blockHeight = await connection.getBlockHeight()\n }\n\n // Stop waiting for tx confirmation\n abortController.abort()\n\n if (!confirmedTx) {\n throw new TransactionError(\n LiFiErrorCode.TransactionExpired,\n 'Transaction has expired: The block height has exceeded the maximum allowed limit.'\n )\n }\n\n if (confirmedTx?.err) {\n const reason =\n typeof confirmedTx.err === 'object'\n ? JSON.stringify(confirmedTx.err)\n : confirmedTx.err\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n `Transaction failed: ${reason}`\n )\n }\n\n // Transaction has been confirmed and we can update the process\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'PENDING',\n {\n txHash: txSignature,\n txLink: `${fromChain.metamask.blockExplorerUrls[0]}tx/${txSignature}`,\n }\n )\n\n if (isBridgeExecution) {\n process = this.statusManager.updateProcess(step, process.type, 'DONE')\n }\n } catch (e: any) {\n const error = await parseSolanaErrors(e, step, process)\n process = this.statusManager.updateProcess(\n step,\n process.type,\n 'FAILED',\n {\n error: {\n message: error.cause.message,\n code: error.code,\n },\n }\n )\n this.statusManager.updateExecution(step, 'FAILED')\n throw error\n }\n }\n\n // STEP 5: Wait for the receiving chain\n const processTxHash = process.txHash\n if (isBridgeExecution) {\n process = this.statusManager.findOrCreateProcess({\n step,\n type: 'RECEIVING_CHAIN',\n status: 'PENDING',\n chainId: toChain.id,\n })\n }\n let statusResponse: FullStatusData\n try {\n if (!processTxHash) {\n throw new Error('Transaction hash is undefined.')\n }\n statusResponse = (await waitForReceivingTransaction(\n processTxHash,\n this.statusManager,\n process.type,\n step\n )) as FullStatusData\n\n const statusReceiving =\n statusResponse.receiving as ExtendedTransactionInfo\n\n process = this.statusManager.updateProcess(step, process.type, 'DONE', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(statusResponse.status, statusResponse.substatus),\n txHash: statusReceiving?.txHash,\n txLink: `${toChain.metamask.blockExplorerUrls[0]}tx/${statusReceiving?.txHash}`,\n })\n\n this.statusManager.updateExecution(step, 'DONE', {\n fromAmount: statusResponse.sending.amount,\n toAmount: statusReceiving?.amount,\n toToken: statusReceiving?.token,\n gasCosts: [\n {\n amount: statusResponse.sending.gasAmount,\n amountUSD: statusResponse.sending.gasAmountUSD,\n token: statusResponse.sending.gasToken,\n estimate: statusResponse.sending.gasUsed,\n limit: statusResponse.sending.gasUsed,\n price: statusResponse.sending.gasPrice,\n type: 'SEND',\n },\n ],\n })\n } catch (e: unknown) {\n const htmlMessage = await getTransactionFailedMessage(\n step,\n process.txLink\n )\n\n process = this.statusManager.updateProcess(step, process.type, 'FAILED', {\n error: {\n code: LiFiErrorCode.TransactionFailed,\n message: 'Failed while waiting for receiving chain.',\n htmlMessage,\n },\n })\n this.statusManager.updateExecution(step, 'FAILED')\n console.warn(e)\n throw e\n }\n\n // DONE\n return step\n }\n}\n","export function base64ToUint8Array(base64String: string) {\n const binaryString = atob(base64String)\n const len = binaryString.length\n const bytes = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i)\n }\n return bytes\n}\n","import { PublicKey } from '@solana/web3.js'\n\nexport function isAddress(address: string): boolean {\n try {\n new PublicKey(address)\n return true\n } catch (error) {\n return false\n }\n}\n","import { isAddress } from './isAddress.js'\n\ninterface SNSResult {\n s: 'ok' | 'error'\n result: string\n}\n\n// Subject to change\n// https://github.com/Bonfida/sns-sdk?tab=readme-ov-file#sdk-proxy\nexport const getSNSAddress = async (name: string) => {\n try {\n if (!name.endsWith('.sol')) {\n return\n }\n // const rpcUrl = await getRpcUrl(ChainId.SOL)\n const snsWorkerUrl = `https://sns-sdk-proxy.bonfida.workers.dev/resolve/${name}`\n const response: Response = await fetch(snsWorkerUrl)\n if (!response.ok) {\n return\n }\n\n const data: SNSResult = await response.json()\n\n if (!isAddress(data.result)) {\n return\n }\n\n return data.result\n } catch (_) {\n // ignore\n return\n }\n}\n","import { ChainType } from '@lifi/types'\nimport type { SignerWalletAdapter } from '@solana/wallet-adapter-base'\nimport { type SDKProvider } from '../types.js'\n\nexport interface SolanaProviderOptions {\n getWalletAdapter?: () => Promise\n}\n\nexport interface SolanaProvider extends SDKProvider {\n setOptions(options: SolanaProviderOptions): void\n}\n\nexport function isSolana(provider: SDKProvider): provider is SolanaProvider {\n return provider.type === ChainType.SVM\n}\n\nexport const TokenProgramAddress = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'\n","import type { ChainId, Token, TokenAmount } from '@lifi/types'\nimport { PublicKey } from '@solana/web3.js'\nimport { SolSystemProgram } from '../../constants.js'\nimport { getSolanaConnection } from './connection.js'\nimport { TokenProgramAddress } from './types.js'\n\nexport const getSolanaBalance = async (\n walletAddress: string,\n tokens: Token[]\n): Promise => {\n if (tokens.length === 0) {\n return []\n }\n const { chainId } = tokens[0]\n tokens.forEach((token) => {\n if (token.chainId !== chainId) {\n console.warn(`Requested tokens have to be on the same chain.`)\n }\n })\n\n return getSolanaBalanceDefault(chainId, tokens, walletAddress)\n}\n\nconst getSolanaBalanceDefault = async (\n _chainId: ChainId,\n tokens: Token[],\n walletAddress: string\n): Promise => {\n const connection = await getSolanaConnection()\n const accountPublicKey = new PublicKey(walletAddress)\n const tokenProgramPublicKey = new PublicKey(TokenProgramAddress)\n const [slot, balance, tokenAccountsByOwner] = await Promise.allSettled([\n connection.getSlot(),\n connection.getBalance(accountPublicKey),\n connection.getParsedTokenAccountsByOwner(accountPublicKey, {\n programId: tokenProgramPublicKey,\n }),\n ])\n const blockNumber = slot.status === 'fulfilled' ? BigInt(slot.value) : 0n\n const solBalance = balance.status === 'fulfilled' ? BigInt(balance.value) : 0n\n const walletTokenAmounts =\n tokenAccountsByOwner.status === 'fulfilled'\n ? tokenAccountsByOwner.value.value.reduce(\n (tokenAmounts, value) => {\n const amount = BigInt(\n value.account.data.parsed.info.tokenAmount.amount\n )\n if (amount > 0n) {\n tokenAmounts[value.account.data.parsed.info.mint] = amount\n }\n return tokenAmounts\n },\n {} as Record\n )\n : {}\n walletTokenAmounts[SolSystemProgram] = solBalance\n const tokenAmounts: TokenAmount[] = tokens.map((token) => {\n if (walletTokenAmounts[token.address]) {\n return {\n ...token,\n amount: walletTokenAmounts[token.address],\n blockNumber,\n }\n }\n return {\n ...token,\n blockNumber,\n }\n })\n return tokenAmounts\n}\n","import type { Abi, Address, TypedData } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type GetChainIdReturnType,\n getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n type AddChainParameters,\n addChain,\n} from '../../actions/wallet/addChain.js'\nimport {\n type DeployContractParameters,\n type DeployContractReturnType,\n deployContract,\n} from '../../actions/wallet/deployContract.js'\nimport {\n type GetAddressesReturnType,\n getAddresses,\n} from '../../actions/wallet/getAddresses.js'\nimport {\n type GetPermissionsReturnType,\n getPermissions,\n} from '../../actions/wallet/getPermissions.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\n type PrepareTransactionRequestReturnType,\n prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n type RequestAddressesReturnType,\n requestAddresses,\n} from '../../actions/wallet/requestAddresses.js'\nimport {\n type RequestPermissionsParameters,\n type RequestPermissionsReturnType,\n requestPermissions,\n} from '../../actions/wallet/requestPermissions.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n type SendTransactionParameters,\n type SendTransactionRequest,\n type SendTransactionReturnType,\n sendTransaction,\n} from '../../actions/wallet/sendTransaction.js'\nimport {\n type SignMessageParameters,\n type SignMessageReturnType,\n signMessage,\n} from '../../actions/wallet/signMessage.js'\nimport {\n type SignTransactionParameters,\n type SignTransactionReturnType,\n signTransaction,\n} from '../../actions/wallet/signTransaction.js'\nimport {\n type SignTypedDataParameters,\n type SignTypedDataReturnType,\n signTypedData,\n} from '../../actions/wallet/signTypedData.js'\nimport {\n type SwitchChainParameters,\n switchChain,\n} from '../../actions/wallet/switchChain.js'\nimport {\n type WatchAssetParameters,\n type WatchAssetReturnType,\n watchAsset,\n} from '../../actions/wallet/watchAsset.js'\nimport {\n type WriteContractParameters,\n type WriteContractReturnType,\n writeContract,\n} from '../../actions/wallet/writeContract.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type WalletActions<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = {\n /**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/addChain\n * - JSON-RPC Methods: [`eth_addEthereumChain`](https://eips.ethereum.org/EIPS/eip-3085)\n *\n * @param args - {@link AddChainParameters}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { optimism } from 'viem/chains'\n *\n * const client = createWalletClient({\n * transport: custom(window.ethereum),\n * })\n * await client.addChain({ chain: optimism })\n */\n addChain: (args: AddChainParameters) => Promise\n /**\n * Deploys a contract to the network, given bytecode and constructor arguments.\n *\n * - Docs: https://viem.sh/docs/contract/deployContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/deploying-contracts\n *\n * @param args - {@link DeployContractParameters}\n * @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link DeployContractReturnType}\n *\n * @example\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const hash = await client.deployContract({\n * abi: [],\n * account: '0x…,\n * bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',\n * })\n */\n deployContract: <\n const abi extends Abi | readonly unknown[],\n chainOverride extends Chain | undefined,\n >(\n args: DeployContractParameters,\n ) => Promise\n /**\n * Returns a list of account addresses owned by the wallet or client.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getAddresses\n * - JSON-RPC Methods: [`eth_accounts`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_accounts)\n *\n * @returns List of account addresses owned by the wallet or client. {@link GetAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const accounts = await client.getAddresses()\n */\n getAddresses: () => Promise\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createWalletClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const chainId = await client.getChainId()\n * // 1\n */\n getChainId: () => Promise\n /**\n * Gets the wallets current permissions.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getPermissions\n * - JSON-RPC Methods: [`wallet_getPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n *\n * @returns The wallet permissions. {@link GetPermissionsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const permissions = await client.getPermissions()\n */\n getPermissions: () => Promise\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\n prepareTransactionRequest: <\n const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Requests a list of accounts managed by a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestAddresses\n * - JSON-RPC Methods: [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102)\n *\n * Sends a request to the wallet, asking for permission to access the user's accounts. After the user accepts the request, it will return a list of accounts (addresses).\n *\n * This API can be useful for dapps that need to access the user's accounts in order to execute transactions or interact with smart contracts.\n *\n * @returns List of accounts managed by a wallet {@link RequestAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const accounts = await client.requestAddresses()\n */\n requestAddresses: () => Promise\n /**\n * Requests permissions for a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestPermissions\n * - JSON-RPC Methods: [`wallet_requestPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n *\n * @param args - {@link RequestPermissionsParameters}\n * @returns The wallet permissions. {@link RequestPermissionsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const permissions = await client.requestPermissions({\n * eth_accounts: {}\n * })\n */\n requestPermissions: (\n args: RequestPermissionsParameters,\n ) => Promise\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const hash = await client.sendRawTransaction({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransaction: (\n args: SendRawTransactionParameters,\n ) => Promise\n /**\n * Creates, signs, and sends a new transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendTransaction\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_sendTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction)\n * - Local Accounts: [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction)\n *\n * @param args - {@link SendTransactionParameters}\n * @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link SendTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const hash = await client.sendTransaction({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 1000000000000000000n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const hash = await client.sendTransaction({\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 1000000000000000000n,\n * })\n */\n sendTransaction: <\n const request extends SendTransactionRequest,\n chainOverride extends Chain | undefined = undefined,\n >(\n args: SendTransactionParameters,\n ) => Promise\n /**\n * Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191): `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signMessage\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`personal_sign`](https://docs.metamask.io/guide/signing-data#personal-sign)\n * - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * With the calculated signature, you can:\n * - use [`verifyMessage`](https://viem.sh/docs/utilities/verifyMessage) to verify the signature,\n * - use [`recoverMessageAddress`](https://viem.sh/docs/utilities/recoverMessageAddress) to recover the signing address from a signature.\n *\n * @param args - {@link SignMessageParameters}\n * @returns The signed message. {@link SignMessageReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const signature = await client.signMessage({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * message: 'hello world',\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const signature = await client.signMessage({\n * message: 'hello world',\n * })\n */\n signMessage: (\n args: SignMessageParameters,\n ) => Promise\n /**\n * Signs a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTransaction\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_signTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n * - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * @param args - {@link SignTransactionParameters}\n * @returns The signed message. {@link SignTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n * const signature = await client.signTransaction(request)\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const request = await client.prepareTransactionRequest({\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n * const signature = await client.signTransaction(request)\n */\n signTransaction: (\n args: SignTransactionParameters,\n ) => Promise\n /**\n * Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191): `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTypedData\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_signTypedData_v4`](https://docs.metamask.io/guide/signing-data#signtypeddata-v4)\n * - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * @param client - Client to use\n * @param args - {@link SignTypedDataParameters}\n * @returns The signed data. {@link SignTypedDataReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const signature = await client.signTypedData({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * domain: {\n * name: 'Ether Mail',\n * version: '1',\n * chainId: 1,\n * verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n * },\n * types: {\n * Person: [\n * { name: 'name', type: 'string' },\n * { name: 'wallet', type: 'address' },\n * ],\n * Mail: [\n * { name: 'from', type: 'Person' },\n * { name: 'to', type: 'Person' },\n * { name: 'contents', type: 'string' },\n * ],\n * },\n * primaryType: 'Mail',\n * message: {\n * from: {\n * name: 'Cow',\n * wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n * },\n * to: {\n * name: 'Bob',\n * wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n * },\n * contents: 'Hello, Bob!',\n * },\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const signature = await client.signTypedData({\n * domain: {\n * name: 'Ether Mail',\n * version: '1',\n * chainId: 1,\n * verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n * },\n * types: {\n * Person: [\n * { name: 'name', type: 'string' },\n * { name: 'wallet', type: 'address' },\n * ],\n * Mail: [\n * { name: 'from', type: 'Person' },\n * { name: 'to', type: 'Person' },\n * { name: 'contents', type: 'string' },\n * ],\n * },\n * primaryType: 'Mail',\n * message: {\n * from: {\n * name: 'Cow',\n * wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n * },\n * to: {\n * name: 'Bob',\n * wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n * },\n * contents: 'Hello, Bob!',\n * },\n * })\n */\n signTypedData: <\n const typedData extends TypedData | { [key: string]: unknown },\n primaryType extends string,\n >(\n args: SignTypedDataParameters,\n ) => Promise\n /**\n * Switch the target chain in a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/switchChain\n * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-3326)\n *\n * @param args - {@link SwitchChainParameters}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet, optimism } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * await client.switchChain({ id: optimism.id })\n */\n switchChain: (args: SwitchChainParameters) => Promise\n /**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/watchAsset\n * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-747)\n *\n * @param args - {@link WatchAssetParameters}\n * @returns Boolean indicating if the token was successfully added. {@link WatchAssetReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const success = await client.watchAsset({\n * type: 'ERC20',\n * options: {\n * address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * decimals: 18,\n * symbol: 'WETH',\n * },\n * })\n */\n watchAsset: (args: WatchAssetParameters) => Promise\n /**\n * Executes a write function on a contract.\n *\n * - Docs: https://viem.sh/docs/contract/writeContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts\n *\n * A \"write\" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, and hence a [Transaction](https://viem.sh/docs/glossary/terms) is needed to be broadcast in order to change the state.\n *\n * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * __Warning: The `write` internally sends a transaction – it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to [simulate the contract write with `contract.simulate`](https://viem.sh/docs/contract/writeContract#usage) before you execute it.__\n *\n * @param args - {@link WriteContractParameters}\n * @returns A [Transaction Hash](https://viem.sh/docs/glossary/terms#hash). {@link WriteContractReturnType}\n *\n * @example\n * import { createWalletClient, custom, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const hash = await client.writeContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n * functionName: 'mint',\n * args: [69420],\n * })\n *\n * @example\n * // With Validation\n * import { createWalletClient, custom, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const { request } = await client.simulateContract({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n * functionName: 'mint',\n * args: [69420],\n * }\n * const hash = await client.writeContract(request)\n */\n writeContract: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName,\n args extends ContractFunctionArgs<\n abi,\n 'payable' | 'nonpayable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n >(\n args: WriteContractParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n >,\n ) => Promise\n}\n\nexport function walletActions<\n transport extends Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(client: Client): WalletActions {\n return {\n addChain: (args) => addChain(client, args),\n deployContract: (args) => deployContract(client, args),\n getAddresses: () => getAddresses(client),\n getChainId: () => getChainId(client),\n getPermissions: () => getPermissions(client),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n requestAddresses: () => requestAddresses(client),\n requestPermissions: (args) => requestPermissions(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n sendTransaction: (args) => sendTransaction(client, args),\n signMessage: (args) => signMessage(client, args),\n signTransaction: (args) => signTransaction(client, args),\n signTypedData: (args) => signTypedData(client, args),\n switchChain: (args) => switchChain(client, args),\n watchAsset: (args) => watchAsset(client, args),\n writeContract: (args) => writeContract(client, args as any),\n }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type AddChainParameters = {\n /** The chain to add to the wallet. */\n chain: Chain\n}\n\nexport type AddChainErrorType =\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/addChain\n * - JSON-RPC Methods: [`eth_addEthereumChain`](https://eips.ethereum.org/EIPS/eip-3085)\n *\n * @param client - Client to use\n * @param parameters - {@link AddChainParameters}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { optimism } from 'viem/chains'\n * import { addChain } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * transport: custom(window.ethereum),\n * })\n * await addChain(client, { chain: optimism })\n */\nexport async function addChain<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client, { chain }: AddChainParameters) {\n const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain\n await client.request(\n {\n method: 'wallet_addEthereumChain',\n params: [\n {\n chainId: numberToHex(id),\n chainName: name,\n nativeCurrency,\n rpcUrls: rpcUrls.default.http,\n blockExplorerUrls: blockExplorers\n ? Object.values(blockExplorers).map(({ url }) => url)\n : undefined,\n },\n ],\n },\n { dedupe: true, retryCount: 0 },\n )\n}\n","import type { Abi } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetChainParameter } from '../../types/chain.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate, UnionOmit } from '../../types/utils.js'\nimport { encodeDeployData } from '../../utils/abi/encodeDeployData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n type SendTransactionErrorType,\n type SendTransactionParameters,\n type SendTransactionReturnType,\n sendTransaction,\n} from './sendTransaction.js'\n\nexport type DeployContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n allArgs = ContractConstructorArgs,\n> = UnionOmit<\n SendTransactionParameters,\n 'accessList' | 'chain' | 'to' | 'data'\n> &\n GetChainParameter &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > & {\n abi: abi\n bytecode: Hex\n }\n\nexport type DeployContractReturnType = SendTransactionReturnType\n\nexport type DeployContractErrorType = SendTransactionErrorType | ErrorType\n\n/**\n * Deploys a contract to the network, given bytecode and constructor arguments.\n *\n * - Docs: https://viem.sh/docs/contract/deployContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/deploying-contracts\n *\n * @param client - Client to use\n * @param parameters - {@link DeployContractParameters}\n * @returns The [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. {@link DeployContractReturnType}\n *\n * @example\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { deployContract } from 'viem/contract'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const hash = await deployContract(client, {\n * abi: [],\n * account: '0x…,\n * bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',\n * })\n */\nexport function deployContract<\n const abi extends Abi | readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined,\n>(\n walletClient: Client,\n parameters: DeployContractParameters,\n): Promise {\n const { abi, args, bytecode, ...request } =\n parameters as DeployContractParameters\n const calldata = encodeDeployData({ abi, args, bytecode })\n return sendTransaction(walletClient, {\n ...request,\n data: calldata,\n } as unknown as SendTransactionParameters)\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetAddressesReturnType = Address[]\n\nexport type GetAddressesErrorType =\n | RequestErrorType\n | ChecksumAddressErrorType\n | ErrorType\n\n/**\n * Returns a list of account addresses owned by the wallet or client.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getAddresses\n * - JSON-RPC Methods: [`eth_accounts`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_accounts)\n *\n * @param client - Client to use\n * @returns List of account addresses owned by the wallet or client. {@link GetAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getAddresses } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const accounts = await getAddresses(client)\n */\nexport async function getAddresses<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client): Promise {\n if (client.account?.type === 'local') return [client.account.address]\n const addresses = await client.request(\n { method: 'eth_accounts' },\n { dedupe: true },\n )\n return addresses.map((address) => checksumAddress(address))\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WalletPermission } from '../../types/eip1193.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetPermissionsReturnType = WalletPermission[]\n\nexport type GetPermissionsErrorType = RequestErrorType | ErrorType\n\n/**\n * Gets the wallets current permissions.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getPermissions\n * - JSON-RPC Methods: [`wallet_getPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n *\n * @param client - Client to use\n * @returns The wallet permissions. {@link GetPermissionsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getPermissions } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const permissions = await getPermissions(client)\n */\nexport async function getPermissions<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client) {\n const permissions = await client.request(\n { method: 'wallet_getPermissions' },\n { dedupe: true },\n )\n return permissions\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport { getAddress } from '../../utils/address/getAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type RequestAddressesReturnType = Address[]\n\nexport type RequestAddressesErrorType = RequestErrorType | ErrorType\n\n/**\n * Requests a list of accounts managed by a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestAddresses\n * - JSON-RPC Methods: [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102)\n *\n * Sends a request to the wallet, asking for permission to access the user's accounts. After the user accepts the request, it will return a list of accounts (addresses).\n *\n * This API can be useful for dapps that need to access the user's accounts in order to execute transactions or interact with smart contracts.\n *\n * @param client - Client to use\n * @returns List of accounts managed by a wallet {@link RequestAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { requestAddresses } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const accounts = await requestAddresses(client)\n */\nexport async function requestAddresses<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n): Promise {\n const addresses = await client.request(\n { method: 'eth_requestAccounts' },\n { dedupe: true, retryCount: 0 },\n )\n return addresses.map((address) => getAddress(address))\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WalletPermission } from '../../types/eip1193.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type RequestPermissionsParameters = Prettify<\n {\n eth_accounts: Record\n } & {\n [key: string]: Record\n }\n>\nexport type RequestPermissionsReturnType = WalletPermission[]\n\nexport type RequestPermissionsErrorType = RequestErrorType | ErrorType\n\n/**\n * Requests permissions for a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestPermissions\n * - JSON-RPC Methods: [`wallet_requestPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n *\n * @param client - Client to use\n * @param parameters - {@link RequestPermissionsParameters}\n * @returns The wallet permissions. {@link RequestPermissionsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { requestPermissions } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const permissions = await requestPermissions(client, {\n * eth_accounts: {}\n * })\n */\nexport async function requestPermissions<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n permissions: RequestPermissionsParameters,\n) {\n return client.request(\n {\n method: 'wallet_requestPermissions',\n params: [permissions],\n },\n { retryCount: 0 },\n )\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignTransactionErrorType as SignTransactionErrorType_account } from '../../accounts/utils/signTransaction.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { AccountNotFoundError } from '../../errors/account.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type {\n TransactionRequest,\n TransactionSerializable,\n TransactionSerialized,\n} from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type AssertCurrentChainErrorType,\n assertCurrentChain,\n} from '../../utils/chain/assertCurrentChain.js'\nimport { numberToHex } from '../../utils/encoding/toHex.js'\nimport type { NumberToHexErrorType } from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport { type GetChainIdErrorType, getChainId } from '../public/getChainId.js'\n\ntype SignTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain,\n> = UnionOmit, 'from'>\n\nexport type SignTransactionParameters<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n request extends SignTransactionRequest<\n chain,\n chainOverride\n > = SignTransactionRequest,\n> = request &\n GetAccountParameter &\n GetChainParameter &\n GetTransactionRequestKzgParameter\n\nexport type SignTransactionReturnType = TransactionSerialized\n\nexport type SignTransactionErrorType =\n | ParseAccountErrorType\n | AssertRequestErrorType\n | GetChainIdErrorType\n | AssertCurrentChainErrorType\n | SignTransactionErrorType_account\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Signs a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTransaction\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_signTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n * - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * @param args - {@link SignTransactionParameters}\n * @returns The signed serialized transaction. {@link SignTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { signTransaction } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const signature = await signTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signTransaction } from 'viem/actions'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const signature = await signTransaction(client, {\n * to: '0x0000000000000000000000000000000000000000',\n * value: 1n,\n * })\n */\nexport async function signTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n const request extends SignTransactionRequest<\n chain,\n chainOverride\n > = SignTransactionRequest,\n>(\n client: Client,\n parameters: SignTransactionParameters,\n): Promise {\n const {\n account: account_ = client.account,\n chain = client.chain,\n ...transaction\n } = parameters\n\n if (!account_)\n throw new AccountNotFoundError({\n docsPath: '/docs/actions/wallet/signTransaction',\n })\n const account = parseAccount(account_)\n\n assertRequest({\n account,\n ...parameters,\n })\n\n const chainId = await getAction(client, getChainId, 'getChainId')({})\n if (chain !== null)\n assertCurrentChain({\n currentChainId: chainId,\n chain,\n })\n\n const formatters = chain?.formatters || client.chain?.formatters\n const format =\n formatters?.transactionRequest?.format || formatTransactionRequest\n\n if (account.signTransaction)\n return account.signTransaction(\n {\n ...transaction,\n chainId,\n } as TransactionSerializable,\n { serializer: client.chain?.serializers?.transaction },\n ) as Promise\n\n return await client.request(\n {\n method: 'eth_signTransaction',\n params: [\n {\n ...format(transaction as unknown as TransactionRequest),\n chainId: numberToHex(chainId),\n from: account.address,\n } as unknown as RpcTransactionRequest,\n ],\n },\n { retryCount: 0 },\n )\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignTypedDataErrorType as SignTypedDataErrorType_account } from '../../accounts/utils/signTypedData.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n AccountNotFoundError,\n type AccountNotFoundErrorType,\n} from '../../errors/account.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport type { IsHexErrorType } from '../../utils/data/isHex.js'\nimport type { StringifyErrorType } from '../../utils/stringify.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n type SerializeTypedDataErrorType,\n type ValidateTypedDataErrorType,\n getTypesForEIP712Domain,\n serializeTypedData,\n validateTypedData,\n} from '../../utils/typedData.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n account extends Account | undefined = undefined,\n ///\n primaryTypes = typedData extends TypedData ? keyof typedData : string,\n> = TypedDataDefinition &\n GetAccountParameter\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n | AccountNotFoundErrorType\n | ParseAccountErrorType\n | GetTypesForEIP712DomainErrorType\n | ValidateTypedDataErrorType\n | StringifyErrorType\n | SignTypedDataErrorType_account\n | IsHexErrorType\n | RequestErrorType\n | SerializeTypedDataErrorType\n | ErrorType\n\n/**\n * Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712): `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(message)))`\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTypedData\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_signTypedData_v4`](https://docs.metamask.io/guide/signing-data#signtypeddata-v4)\n * - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * @param client - Client to use\n * @param parameters - {@link SignTypedDataParameters}\n * @returns The signed data. {@link SignTypedDataReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { signTypedData } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const signature = await signTypedData(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * domain: {\n * name: 'Ether Mail',\n * version: '1',\n * chainId: 1,\n * verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n * },\n * types: {\n * Person: [\n * { name: 'name', type: 'string' },\n * { name: 'wallet', type: 'address' },\n * ],\n * Mail: [\n * { name: 'from', type: 'Person' },\n * { name: 'to', type: 'Person' },\n * { name: 'contents', type: 'string' },\n * ],\n * },\n * primaryType: 'Mail',\n * message: {\n * from: {\n * name: 'Cow',\n * wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n * },\n * to: {\n * name: 'Bob',\n * wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n * },\n * contents: 'Hello, Bob!',\n * },\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signTypedData } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const signature = await signTypedData(client, {\n * domain: {\n * name: 'Ether Mail',\n * version: '1',\n * chainId: 1,\n * verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n * },\n * types: {\n * Person: [\n * { name: 'name', type: 'string' },\n * { name: 'wallet', type: 'address' },\n * ],\n * Mail: [\n * { name: 'from', type: 'Person' },\n * { name: 'to', type: 'Person' },\n * { name: 'contents', type: 'string' },\n * ],\n * },\n * primaryType: 'Mail',\n * message: {\n * from: {\n * name: 'Cow',\n * wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n * },\n * to: {\n * name: 'Bob',\n * wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n * },\n * contents: 'Hello, Bob!',\n * },\n * })\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client,\n parameters: SignTypedDataParameters,\n): Promise {\n const {\n account: account_ = client.account,\n domain,\n message,\n primaryType,\n } = parameters as unknown as SignTypedDataParameters\n\n if (!account_)\n throw new AccountNotFoundError({\n docsPath: '/docs/actions/wallet/signTypedData',\n })\n const account = parseAccount(account_)\n\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\n }\n\n // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n // as we can't statically check this with TypeScript.\n validateTypedData({ domain, message, primaryType, types })\n\n if (account.signTypedData)\n return account.signTypedData({ domain, message, primaryType, types })\n\n const typedData = serializeTypedData({ domain, message, primaryType, types })\n return client.request(\n {\n method: 'eth_signTypedData_v4',\n params: [account.address, typedData],\n },\n { retryCount: 0 },\n )\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type SwitchChainParameters = {\n /** ID of Chain to switch to */\n id: Chain['id']\n}\n\nexport type SwitchChainErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Switch the target chain in a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/switchChain\n * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-3326)\n *\n * @param client - Client to use\n * @param parameters - {@link SwitchChainParameters}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet, optimism } from 'viem/chains'\n * import { switchChain } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * await switchChain(client, { id: optimism.id })\n */\nexport async function switchChain<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client, { id }: SwitchChainParameters) {\n await client.request(\n {\n method: 'wallet_switchEthereumChain',\n params: [\n {\n chainId: numberToHex(id),\n },\n ],\n },\n { retryCount: 0 },\n )\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WatchAssetParams } from '../../types/eip1193.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type WatchAssetParameters = WatchAssetParams\nexport type WatchAssetReturnType = boolean\nexport type WatchAssetErrorType = RequestErrorType | ErrorType\n\n/**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/watchAsset\n * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-747)\n *\n * @param client - Client to use\n * @param parameters - {@link WatchAssetParameters}\n * @returns Boolean indicating if the token was successfully added. {@link WatchAssetReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchAsset } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const success = await watchAsset(client, {\n * type: 'ERC20',\n * options: {\n * address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * decimals: 18,\n * symbol: 'WETH',\n * },\n * })\n */\nexport async function watchAsset<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client,\n params: WatchAssetParameters,\n): Promise {\n const added = await client.request(\n {\n method: 'wallet_watchAsset',\n params,\n },\n { retryCount: 0 },\n )\n return added\n}\n","import { type Account, type WalletClient, walletActions } from 'viem'\n\nimport type { Config } from '../createConfig.js'\nimport type { BaseErrorType, ErrorType } from '../errors/base.js'\nimport type { Compute } from '../types/utils.js'\nimport {\n type GetConnectorClientErrorType,\n type GetConnectorClientParameters,\n getConnectorClient,\n} from './getConnectorClient.js'\n\nexport type GetWalletClientParameters<\n config extends Config = Config,\n chainId extends\n config['chains'][number]['id'] = config['chains'][number]['id'],\n> = GetConnectorClientParameters\n\nexport type GetWalletClientReturnType<\n config extends Config = Config,\n chainId extends\n config['chains'][number]['id'] = config['chains'][number]['id'],\n> = Compute<\n WalletClient<\n config['_internal']['transports'][chainId],\n Extract,\n Account\n >\n>\n\nexport type GetWalletClientErrorType =\n // getConnectorClient()\n | GetConnectorClientErrorType\n // base\n | BaseErrorType\n | ErrorType\n\nexport async function getWalletClient<\n config extends Config,\n chainId extends config['chains'][number]['id'],\n>(\n config: config,\n parameters: GetWalletClientParameters = {},\n): Promise> {\n const client = await getConnectorClient(config, parameters)\n client.extend(walletActions)\n\n // @ts-ignore\n return client.extend(walletActions) as unknown as GetWalletClientReturnType<\n config,\n chainId\n >\n}\n","import type { SDKProvider } from '@lifi/sdk';\nimport { ChainType, EVM, Solana, config } from '@lifi/sdk';\nimport type { SignerWalletAdapter } from '@solana/wallet-adapter-base';\nimport { useWallet } from '@solana/wallet-adapter-react';\nimport { getWalletClient, switchChain } from '@wagmi/core';\nimport { useEffect } from 'react';\nimport { useConfig } from 'wagmi';\nimport { useWidgetConfig } from '../WidgetProvider/WidgetProvider.js';\n\nexport const SDKProviders = () => {\n const { sdkConfig } = useWidgetConfig();\n const { wallet } = useWallet();\n const wagmiConfig = useConfig();\n\n useEffect(() => {\n // Configure SDK Providers\n const providers: SDKProvider[] = [];\n const hasConfiguredEVMProvider = sdkConfig?.providers?.some(\n (provider) => provider.type === ChainType.EVM,\n );\n const hasConfiguredSVMProvider = sdkConfig?.providers?.some(\n (provider) => provider.type === ChainType.SVM,\n );\n if (!hasConfiguredEVMProvider) {\n providers.push(\n EVM({\n getWalletClient: () => getWalletClient(wagmiConfig),\n switchChain: async (chainId: number) => {\n const chain = await switchChain(wagmiConfig, { chainId });\n return getWalletClient(wagmiConfig, { chainId: chain.id });\n },\n }),\n );\n }\n if (!hasConfiguredSVMProvider) {\n providers.push(\n Solana({\n async getWalletAdapter() {\n return wallet?.adapter as SignerWalletAdapter;\n },\n }),\n );\n }\n if (sdkConfig?.providers?.length) {\n providers.push(...sdkConfig?.providers);\n }\n config.setProviders(providers);\n }, [sdkConfig?.providers, wagmiConfig, wallet?.adapter]);\n\n return null;\n};\n","import { ChainType } from '@lifi/types'\nimport { isAddress } from 'viem'\nimport type { StepExecutorOptions } from '../types.js'\nimport { EVMStepExecutor } from './EVMStepExecutor.js'\nimport { getENSAddress } from './getENSAddress.js'\nimport { getEVMBalance } from './getEVMBalance.js'\nimport type { EVMProvider, EVMProviderOptions } from './types.js'\n\nexport function EVM(options?: EVMProviderOptions): EVMProvider {\n const _options: EVMProviderOptions = options ?? {}\n return {\n get type() {\n return ChainType.EVM\n },\n get multisig() {\n return _options.multisig\n },\n isAddress,\n resolveAddress: getENSAddress,\n getBalance: getEVMBalance,\n async getStepExecutor(\n options: StepExecutorOptions\n ): Promise {\n if (!_options.getWalletClient) {\n throw new Error(`Client is not provided.`)\n }\n\n const walletClient = await _options.getWalletClient()\n\n const executor = new EVMStepExecutor({\n client: walletClient,\n multisig: _options.multisig,\n routeId: options.routeId,\n executionOptions: {\n ...options.executionOptions,\n switchChainHook:\n _options.switchChain ?? options.executionOptions?.switchChainHook,\n },\n })\n\n return executor\n },\n setOptions(options: EVMProviderOptions) {\n Object.assign(_options, options)\n },\n }\n}\n","import { ChainType } from '@lifi/types'\nimport type { StepExecutorOptions } from '../types.js'\nimport { SolanaStepExecutor } from './SolanaStepExecutor.js'\nimport { getSNSAddress } from './getSNSAddress.js'\nimport { getSolanaBalance } from './getSolanaBalance.js'\nimport { isAddress } from './isAddress.js'\nimport type { SolanaProvider, SolanaProviderOptions } from './types.js'\n\nexport function Solana(options?: SolanaProviderOptions): SolanaProvider {\n const _options: SolanaProviderOptions = options ?? {}\n return {\n get type() {\n return ChainType.SVM\n },\n isAddress,\n resolveAddress: getSNSAddress,\n getBalance: getSolanaBalance,\n async getStepExecutor(\n options: StepExecutorOptions\n ): Promise {\n if (!_options.getWalletAdapter) {\n throw new Error(`getWalletAdapter is not provided.`)\n }\n\n const walletAdapter = await _options.getWalletAdapter()\n\n const executor = new SolanaStepExecutor({\n walletAdapter,\n routeId: options.routeId,\n executionOptions: {\n ...options.executionOptions,\n },\n })\n\n return executor\n },\n setOptions(options: SolanaProviderOptions) {\n Object.assign(_options, options)\n },\n }\n}\n","import { type Connection } from '@solana/web3.js';\nimport { createContext, useContext } from 'react';\n\nexport interface ConnectionContextState {\n connection: Connection;\n}\n\nexport const ConnectionContext = createContext({} as ConnectionContextState);\n\nexport function useConnection(): ConnectionContextState {\n return useContext(ConnectionContext);\n}\n","import type { WalletAdapter } from './adapter.js';\nimport type { MessageSignerWalletAdapter, SignerWalletAdapter, SignInMessageSignerWalletAdapter } from './signer.js';\nimport type { StandardWalletAdapter } from './standard.js';\n\nexport type Adapter =\n | WalletAdapter\n | SignerWalletAdapter\n | MessageSignerWalletAdapter\n | SignInMessageSignerWalletAdapter\n | StandardWalletAdapter;\n\nexport enum WalletAdapterNetwork {\n Mainnet = 'mainnet-beta',\n Testnet = 'testnet',\n Devnet = 'devnet',\n}\n","import { Connection, type ConnectionConfig } from '@solana/web3.js';\nimport React, { type FC, type ReactNode, useMemo } from 'react';\nimport { ConnectionContext } from './useConnection.js';\n\nexport interface ConnectionProviderProps {\n children: ReactNode;\n endpoint: string;\n config?: ConnectionConfig;\n}\n\nexport const ConnectionProvider: FC = ({\n children,\n endpoint,\n config = { commitment: 'confirmed' },\n}) => {\n const connection = useMemo(() => new Connection(endpoint, config), [endpoint, config]);\n\n return {children};\n};\n","import type { Transaction, TransactionVersion, VersionedTransaction } from '@solana/web3.js';\n\nexport type SupportedTransactionVersions = ReadonlySet | null | undefined;\n\nexport type TransactionOrVersionedTransaction = S extends null | undefined\n ? Transaction\n : Transaction | VersionedTransaction;\n\nexport function isVersionedTransaction(\n transaction: Transaction | VersionedTransaction\n): transaction is VersionedTransaction {\n return 'version' in transaction;\n}\n","import type { SolanaSignInInput, SolanaSignInOutput } from '@solana/wallet-standard-features';\nimport type { Connection, TransactionSignature } from '@solana/web3.js';\nimport {\n BaseWalletAdapter,\n type SendTransactionOptions,\n type WalletAdapter,\n type WalletAdapterProps,\n} from './adapter.js';\nimport { WalletSendTransactionError, WalletSignTransactionError } from './errors.js';\nimport { isVersionedTransaction, type TransactionOrVersionedTransaction } from './transaction.js';\n\nexport interface SignerWalletAdapterProps extends WalletAdapterProps {\n signTransaction>(\n transaction: T\n ): Promise;\n signAllTransactions>(\n transactions: T[]\n ): Promise;\n}\n\nexport type SignerWalletAdapter = WalletAdapter & SignerWalletAdapterProps;\n\nexport abstract class BaseSignerWalletAdapter\n extends BaseWalletAdapter\n implements SignerWalletAdapter\n{\n async sendTransaction(\n transaction: TransactionOrVersionedTransaction,\n connection: Connection,\n options: SendTransactionOptions = {}\n ): Promise {\n let emit = true;\n try {\n if (isVersionedTransaction(transaction)) {\n if (!this.supportedTransactionVersions)\n throw new WalletSendTransactionError(\n `Sending versioned transactions isn't supported by this wallet`\n );\n\n if (!this.supportedTransactionVersions.has(transaction.version))\n throw new WalletSendTransactionError(\n `Sending transaction version ${transaction.version} isn't supported by this wallet`\n );\n\n try {\n transaction = await this.signTransaction(transaction);\n\n const rawTransaction = transaction.serialize();\n\n return await connection.sendRawTransaction(rawTransaction, options);\n } catch (error: any) {\n // If the error was thrown by `signTransaction`, rethrow it and don't emit a duplicate event\n if (error instanceof WalletSignTransactionError) {\n emit = false;\n throw error;\n }\n throw new WalletSendTransactionError(error?.message, error);\n }\n } else {\n try {\n const { signers, ...sendOptions } = options;\n\n transaction = await this.prepareTransaction(transaction, connection, sendOptions);\n\n signers?.length && transaction.partialSign(...signers);\n\n transaction = await this.signTransaction(transaction);\n\n const rawTransaction = transaction.serialize();\n\n return await connection.sendRawTransaction(rawTransaction, sendOptions);\n } catch (error: any) {\n // If the error was thrown by `signTransaction`, rethrow it and don't emit a duplicate event\n if (error instanceof WalletSignTransactionError) {\n emit = false;\n throw error;\n }\n throw new WalletSendTransactionError(error?.message, error);\n }\n }\n } catch (error: any) {\n if (emit) {\n this.emit('error', error);\n }\n throw error;\n }\n }\n\n abstract signTransaction>(\n transaction: T\n ): Promise;\n\n async signAllTransactions>(\n transactions: T[]\n ): Promise {\n for (const transaction of transactions) {\n if (isVersionedTransaction(transaction)) {\n if (!this.supportedTransactionVersions)\n throw new WalletSignTransactionError(\n `Signing versioned transactions isn't supported by this wallet`\n );\n\n if (!this.supportedTransactionVersions.has(transaction.version))\n throw new WalletSignTransactionError(\n `Signing transaction version ${transaction.version} isn't supported by this wallet`\n );\n }\n }\n\n const signedTransactions: T[] = [];\n for (const transaction of transactions) {\n signedTransactions.push(await this.signTransaction(transaction));\n }\n return signedTransactions;\n }\n}\n\nexport interface MessageSignerWalletAdapterProps extends WalletAdapterProps {\n signMessage(message: Uint8Array): Promise;\n}\n\nexport type MessageSignerWalletAdapter = WalletAdapter &\n MessageSignerWalletAdapterProps;\n\nexport abstract class BaseMessageSignerWalletAdapter\n extends BaseSignerWalletAdapter\n implements MessageSignerWalletAdapter\n{\n abstract signMessage(message: Uint8Array): Promise;\n}\n\nexport interface SignInMessageSignerWalletAdapterProps extends WalletAdapterProps {\n signIn(input?: SolanaSignInInput): Promise;\n}\n\nexport type SignInMessageSignerWalletAdapter = WalletAdapter &\n SignInMessageSignerWalletAdapterProps;\n\nexport abstract class BaseSignInMessageSignerWalletAdapter\n extends BaseMessageSignerWalletAdapter\n implements SignInMessageSignerWalletAdapter\n{\n abstract signIn(input?: SolanaSignInInput): Promise;\n}\n","import type { SolanaSignInInput, SolanaSignInOutput } from '@solana/wallet-standard-features';\nimport { verifyMessageSignature } from './signMessage.js';\nimport { arraysEqual } from './util.js';\n\n/**\n * TODO: docs\n */\nexport function verifySignIn(input: SolanaSignInInput, output: SolanaSignInOutput): boolean {\n const {\n signedMessage,\n signature,\n account: { publicKey },\n } = output;\n const message = deriveSignInMessage(input, output);\n return !!message && verifyMessageSignature({ message, signedMessage, signature, publicKey });\n}\n\n/**\n * TODO: docs\n */\nexport function deriveSignInMessage(input: SolanaSignInInput, output: SolanaSignInOutput): Uint8Array | null {\n const text = deriveSignInMessageText(input, output);\n if (!text) return null;\n return new TextEncoder().encode(text);\n}\n\n/**\n * TODO: docs\n */\nexport function deriveSignInMessageText(input: SolanaSignInInput, output: SolanaSignInOutput): string | null {\n const parsed = parseSignInMessage(output.signedMessage);\n if (!parsed) return null;\n\n if (input.domain && input.domain !== parsed.domain) return null;\n if (input.address && input.address !== parsed.address) return null;\n if (input.statement !== parsed.statement) return null;\n if (input.uri !== parsed.uri) return null;\n if (input.version !== parsed.version) return null;\n if (input.chainId !== parsed.chainId) return null;\n if (input.nonce !== parsed.nonce) return null;\n if (input.issuedAt !== parsed.issuedAt) return null;\n if (input.expirationTime !== parsed.expirationTime) return null;\n if (input.notBefore !== parsed.notBefore) return null;\n if (input.requestId !== parsed.requestId) return null;\n if (input.resources) {\n if (!parsed.resources) return null;\n if (!arraysEqual(input.resources, parsed.resources)) return null;\n } else if (parsed.resources) return null;\n\n return createSignInMessageText(parsed);\n}\n\n/**\n * TODO: docs\n */\nexport type SolanaSignInInputWithRequiredFields = SolanaSignInInput &\n Required>;\n\n/**\n * TODO: docs\n */\nexport function parseSignInMessage(message: Uint8Array): SolanaSignInInputWithRequiredFields | null {\n const text = new TextDecoder().decode(message);\n return parseSignInMessageText(text);\n}\n\n// TODO: implement https://github.com/solana-labs/solana/blob/master/docs/src/proposals/off-chain-message-signing.md\nconst DOMAIN = '(?[^\\\\n]+?) wants you to sign in with your Solana account:\\\\n';\nconst ADDRESS = '(?
[^\\\\n]+)(?:\\\\n|$)';\nconst STATEMENT = '(?:\\\\n(?[\\\\S\\\\s]*?)(?:\\\\n|$))??';\nconst URI = '(?:\\\\nURI: (?[^\\\\n]+))?';\nconst VERSION = '(?:\\\\nVersion: (?[^\\\\n]+))?';\nconst CHAIN_ID = '(?:\\\\nChain ID: (?[^\\\\n]+))?';\nconst NONCE = '(?:\\\\nNonce: (?[^\\\\n]+))?';\nconst ISSUED_AT = '(?:\\\\nIssued At: (?[^\\\\n]+))?';\nconst EXPIRATION_TIME = '(?:\\\\nExpiration Time: (?[^\\\\n]+))?';\nconst NOT_BEFORE = '(?:\\\\nNot Before: (?[^\\\\n]+))?';\nconst REQUEST_ID = '(?:\\\\nRequest ID: (?[^\\\\n]+))?';\nconst RESOURCES = '(?:\\\\nResources:(?(?:\\\\n- [^\\\\n]+)*))?';\nconst FIELDS = `${URI}${VERSION}${CHAIN_ID}${NONCE}${ISSUED_AT}${EXPIRATION_TIME}${NOT_BEFORE}${REQUEST_ID}${RESOURCES}`;\nconst MESSAGE = new RegExp(`^${DOMAIN}${ADDRESS}${STATEMENT}${FIELDS}\\\\n*$`);\n\n/**\n * TODO: docs\n */\nexport function parseSignInMessageText(text: string): SolanaSignInInputWithRequiredFields | null {\n const match = MESSAGE.exec(text);\n if (!match) return null;\n const groups = match.groups;\n if (!groups) return null;\n\n return {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n domain: groups.domain!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n address: groups.address!,\n statement: groups.statement,\n uri: groups.uri,\n version: groups.version,\n nonce: groups.nonce,\n chainId: groups.chainId,\n issuedAt: groups.issuedAt,\n expirationTime: groups.expirationTime,\n notBefore: groups.notBefore,\n requestId: groups.requestId,\n resources: groups.resources?.split('\\n- ').slice(1),\n };\n}\n\n/**\n * TODO: docs\n */\nexport function createSignInMessage(input: SolanaSignInInputWithRequiredFields): Uint8Array {\n const text = createSignInMessageText(input);\n return new TextEncoder().encode(text);\n}\n\n/**\n * TODO: docs\n */\nexport function createSignInMessageText(input: SolanaSignInInputWithRequiredFields): string {\n // ${domain} wants you to sign in with your Solana account:\n // ${address}\n //\n // ${statement}\n //\n // URI: ${uri}\n // Version: ${version}\n // Chain ID: ${chain}\n // Nonce: ${nonce}\n // Issued At: ${issued-at}\n // Expiration Time: ${expiration-time}\n // Not Before: ${not-before}\n // Request ID: ${request-id}\n // Resources:\n // - ${resources[0]}\n // - ${resources[1]}\n // ...\n // - ${resources[n]}\n\n let message = `${input.domain} wants you to sign in with your Solana account:\\n`;\n message += `${input.address}`;\n\n if (input.statement) {\n message += `\\n\\n${input.statement}`;\n }\n\n const fields: string[] = [];\n if (input.uri) {\n fields.push(`URI: ${input.uri}`);\n }\n if (input.version) {\n fields.push(`Version: ${input.version}`);\n }\n if (input.chainId) {\n fields.push(`Chain ID: ${input.chainId}`);\n }\n if (input.nonce) {\n fields.push(`Nonce: ${input.nonce}`);\n }\n if (input.issuedAt) {\n fields.push(`Issued At: ${input.issuedAt}`);\n }\n if (input.expirationTime) {\n fields.push(`Expiration Time: ${input.expirationTime}`);\n }\n if (input.notBefore) {\n fields.push(`Not Before: ${input.notBefore}`);\n }\n if (input.requestId) {\n fields.push(`Request ID: ${input.requestId}`);\n }\n if (input.resources) {\n fields.push(`Resources:`);\n for (const resource of input.resources) {\n fields.push(`- ${resource}`);\n }\n }\n if (fields.length) {\n message += `\\n\\n${fields.join('\\n')}`;\n }\n\n return message;\n}\n","import { createSignInMessageText } from '@solana/wallet-standard-util';\n\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nconst SolanaMobileWalletAdapterErrorCode = {\n ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: 'ERROR_ASSOCIATION_PORT_OUT_OF_RANGE',\n ERROR_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL',\n ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED',\n ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED',\n ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT',\n ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND',\n ERROR_INVALID_PROTOCOL_VERSION: 'ERROR_INVALID_PROTOCOL_VERSION',\n};\nclass SolanaMobileWalletAdapterError extends Error {\n constructor(...args) {\n const [code, message, data] = args;\n super(message);\n this.code = code;\n this.data = data;\n this.name = 'SolanaMobileWalletAdapterError';\n }\n}\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nconst SolanaMobileWalletAdapterProtocolErrorCode = {\n // Keep these in sync with `mobilewalletadapter/common/ProtocolContract.java`.\n ERROR_AUTHORIZATION_FAILED: -1,\n ERROR_INVALID_PAYLOADS: -2,\n ERROR_NOT_SIGNED: -3,\n ERROR_NOT_SUBMITTED: -4,\n ERROR_TOO_MANY_PAYLOADS: -5,\n ERROR_ATTEST_ORIGIN_ANDROID: -100,\n};\nclass SolanaMobileWalletAdapterProtocolError extends Error {\n constructor(...args) {\n const [jsonRpcMessageId, code, message, data] = args;\n super(message);\n this.code = code;\n this.data = data;\n this.jsonRpcMessageId = jsonRpcMessageId;\n this.name = 'SolanaMobileWalletAdapterProtocolError';\n }\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\n\nfunction createHelloReq(ecdhPublicKey, associationKeypairPrivateKey) {\n return __awaiter(this, void 0, void 0, function* () {\n const publicKeyBuffer = yield crypto.subtle.exportKey('raw', ecdhPublicKey);\n const signatureBuffer = yield crypto.subtle.sign({ hash: 'SHA-256', name: 'ECDSA' }, associationKeypairPrivateKey, publicKeyBuffer);\n const response = new Uint8Array(publicKeyBuffer.byteLength + signatureBuffer.byteLength);\n response.set(new Uint8Array(publicKeyBuffer), 0);\n response.set(new Uint8Array(signatureBuffer), publicKeyBuffer.byteLength);\n return response;\n });\n}\n\nfunction encode(input) {\n return window.btoa(input);\n}\n\nfunction createSIWSMessage(payload) {\n return createSignInMessageText(payload);\n}\nfunction createSIWSMessageBase64(payload) {\n return encode(createSIWSMessage(payload));\n}\n\n// optional features\nconst SolanaSignTransactions = 'solana:signTransactions';\nconst SolanaCloneAuthorization = 'solana:cloneAuthorization';\nconst SolanaSignInWithSolana = 'solana:signInWithSolana';\n\n/**\n * Creates a {@link MobileWallet} proxy that handles backwards compatibility and API to RPC conversion.\n *\n * @param protocolVersion the protocol version in use for this session/request\n * @param protocolRequestHandler callback function that handles sending the RPC request to the wallet endpoint.\n * @returns a {@link MobileWallet} proxy\n */\nfunction createMobileWalletProxy(protocolVersion, protocolRequestHandler) {\n return new Proxy({}, {\n get(target, p) {\n if (target[p] == null) {\n target[p] = function (inputParams) {\n return __awaiter(this, void 0, void 0, function* () {\n const { method, params } = handleMobileWalletRequest(p, inputParams, protocolVersion);\n const result = yield protocolRequestHandler(method, params);\n // if the request tried to sign in but the wallet did not return a sign in result, fallback on message signing\n if (method === 'authorize' && params.sign_in_payload && !result.sign_in_result) {\n result['sign_in_result'] = yield signInFallback(params.sign_in_payload, result, protocolRequestHandler);\n }\n return handleMobileWalletResponse(p, result, protocolVersion);\n });\n };\n }\n return target[p];\n },\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n });\n}\n/**\n * Handles all {@link MobileWallet} API requests and determines the correct MWA RPC method and params to call.\n * This handles backwards compatibility, based on the provided @protocolVersion.\n *\n * @param methodName the name of {@link MobileWallet} method that was called\n * @param methodParams the parameters that were passed to the method\n * @param protocolVersion the protocol version in use for this session/request\n * @returns the RPC request method and params that should be sent to the wallet endpoint\n */\nfunction handleMobileWalletRequest(methodName, methodParams, protocolVersion) {\n let params = methodParams;\n let method = methodName\n .toString()\n .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)\n .toLowerCase();\n switch (methodName) {\n case 'authorize': {\n let { chain } = params;\n if (protocolVersion === 'legacy') {\n switch (chain) {\n case 'solana:testnet': {\n chain = 'testnet';\n break;\n }\n case 'solana:devnet': {\n chain = 'devnet';\n break;\n }\n case 'solana:mainnet': {\n chain = 'mainnet-beta';\n break;\n }\n default: {\n chain = params.cluster;\n }\n }\n params.cluster = chain;\n }\n else {\n switch (chain) {\n case 'testnet':\n case 'devnet': {\n chain = `solana:${chain}`;\n break;\n }\n case 'mainnet-beta': {\n chain = 'solana:mainnet';\n break;\n }\n }\n params.chain = chain;\n }\n }\n case 'reauthorize': {\n const { auth_token, identity } = params;\n if (auth_token) {\n switch (protocolVersion) {\n case 'legacy': {\n method = 'reauthorize';\n params = { auth_token: auth_token, identity: identity };\n break;\n }\n default: {\n method = 'authorize';\n break;\n }\n }\n }\n break;\n }\n }\n return { method, params };\n}\n/**\n * Handles all {@link MobileWallet} API responses and modifies the response for backwards compatibility, if needed\n *\n * @param method the {@link MobileWallet} method that was called\n * @param response the original response that was returned by the method call\n * @param protocolVersion the protocol version in use for this session/request\n * @returns the possibly modified response\n */\nfunction handleMobileWalletResponse(method, response, protocolVersion) {\n switch (method) {\n case 'getCapabilities': {\n const capabilities = response;\n switch (protocolVersion) {\n case 'legacy': {\n const features = [SolanaSignTransactions];\n if (capabilities.supports_clone_authorization === true) {\n features.push(SolanaCloneAuthorization);\n }\n return Object.assign(Object.assign({}, capabilities), { features: features });\n }\n case 'v1': {\n return Object.assign(Object.assign({}, capabilities), { supports_sign_and_send_transactions: true, supports_clone_authorization: capabilities.features.includes(SolanaCloneAuthorization) });\n }\n }\n }\n }\n return response;\n}\nfunction signInFallback(signInPayload, authorizationResult, protocolRequestHandler) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const domain = (_a = signInPayload.domain) !== null && _a !== void 0 ? _a : window.location.host;\n const address = authorizationResult.accounts[0].address;\n const siwsMessage = createSIWSMessageBase64(Object.assign(Object.assign({}, signInPayload), { domain, address }));\n const signMessageResult = yield protocolRequestHandler('sign_messages', {\n addresses: [address],\n payloads: [siwsMessage]\n });\n const signInResult = {\n address: address,\n signed_message: siwsMessage,\n signature: signMessageResult.signed_payloads[0].slice(siwsMessage.length)\n };\n return signInResult;\n });\n}\n\nconst SEQUENCE_NUMBER_BYTES = 4;\nfunction createSequenceNumberVector(sequenceNumber) {\n if (sequenceNumber >= 4294967296) {\n throw new Error('Outbound sequence number overflow. The maximum sequence number is 32-bytes.');\n }\n const byteArray = new ArrayBuffer(SEQUENCE_NUMBER_BYTES);\n const view = new DataView(byteArray);\n view.setUint32(0, sequenceNumber, /* littleEndian */ false);\n return new Uint8Array(byteArray);\n}\n\nconst INITIALIZATION_VECTOR_BYTES = 12;\nconst ENCODED_PUBLIC_KEY_LENGTH_BYTES = 65;\nfunction encryptMessage(plaintext, sequenceNumber, sharedSecret) {\n return __awaiter(this, void 0, void 0, function* () {\n const sequenceNumberVector = createSequenceNumberVector(sequenceNumber);\n const initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES);\n crypto.getRandomValues(initializationVector);\n const ciphertext = yield crypto.subtle.encrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, new TextEncoder().encode(plaintext));\n const response = new Uint8Array(sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength);\n response.set(new Uint8Array(sequenceNumberVector), 0);\n response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength);\n response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength);\n return response;\n });\n}\nfunction decryptMessage(message, sharedSecret) {\n return __awaiter(this, void 0, void 0, function* () {\n const sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES);\n const initializationVector = message.slice(SEQUENCE_NUMBER_BYTES, SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);\n const ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES);\n const plaintextBuffer = yield crypto.subtle.decrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, ciphertext);\n const plaintext = getUtf8Decoder().decode(plaintextBuffer);\n return plaintext;\n });\n}\nfunction getAlgorithmParams(sequenceNumber, initializationVector) {\n return {\n additionalData: sequenceNumber,\n iv: initializationVector,\n name: 'AES-GCM',\n tagLength: 128, // 16 byte tag => 128 bits\n };\n}\nlet _utf8Decoder;\nfunction getUtf8Decoder() {\n if (_utf8Decoder === undefined) {\n _utf8Decoder = new TextDecoder('utf-8');\n }\n return _utf8Decoder;\n}\n\nfunction generateAssociationKeypair() {\n return __awaiter(this, void 0, void 0, function* () {\n return yield crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: 'P-256',\n }, false /* extractable */, ['sign'] /* keyUsages */);\n });\n}\n\nfunction generateECDHKeypair() {\n return __awaiter(this, void 0, void 0, function* () {\n return yield crypto.subtle.generateKey({\n name: 'ECDH',\n namedCurve: 'P-256',\n }, false /* extractable */, ['deriveKey', 'deriveBits'] /* keyUsages */);\n });\n}\n\nfunction encryptJsonRpcMessage(jsonRpcMessage, sharedSecret) {\n return __awaiter(this, void 0, void 0, function* () {\n const plaintext = JSON.stringify(jsonRpcMessage);\n const sequenceNumber = jsonRpcMessage.id;\n return encryptMessage(plaintext, sequenceNumber, sharedSecret);\n });\n}\nfunction decryptJsonRpcMessage(message, sharedSecret) {\n return __awaiter(this, void 0, void 0, function* () {\n const plaintext = yield decryptMessage(message, sharedSecret);\n const jsonRpcMessage = JSON.parse(plaintext);\n if (Object.hasOwnProperty.call(jsonRpcMessage, 'error')) {\n throw new SolanaMobileWalletAdapterProtocolError(jsonRpcMessage.id, jsonRpcMessage.error.code, jsonRpcMessage.error.message);\n }\n return jsonRpcMessage;\n });\n}\n\nfunction parseHelloRsp(payloadBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint.\nassociationPublicKey, ecdhPrivateKey) {\n return __awaiter(this, void 0, void 0, function* () {\n const [associationPublicKeyBuffer, walletPublicKey] = yield Promise.all([\n crypto.subtle.exportKey('raw', associationPublicKey),\n crypto.subtle.importKey('raw', payloadBuffer.slice(0, ENCODED_PUBLIC_KEY_LENGTH_BYTES), { name: 'ECDH', namedCurve: 'P-256' }, false /* extractable */, [] /* keyUsages */),\n ]);\n const sharedSecret = yield crypto.subtle.deriveBits({ name: 'ECDH', public: walletPublicKey }, ecdhPrivateKey, 256);\n const ecdhSecretKey = yield crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false /* extractable */, ['deriveKey'] /* keyUsages */);\n const aesKeyMaterialVal = yield crypto.subtle.deriveKey({\n name: 'HKDF',\n hash: 'SHA-256',\n salt: new Uint8Array(associationPublicKeyBuffer),\n info: new Uint8Array(),\n }, ecdhSecretKey, { name: 'AES-GCM', length: 128 }, false /* extractable */, ['encrypt', 'decrypt']);\n return aesKeyMaterialVal;\n });\n}\n\nfunction parseSessionProps(message, sharedSecret) {\n return __awaiter(this, void 0, void 0, function* () {\n const plaintext = yield decryptMessage(message, sharedSecret);\n const jsonProperties = JSON.parse(plaintext);\n let protocolVersion = 'legacy';\n if (Object.hasOwnProperty.call(jsonProperties, 'v')) {\n switch (jsonProperties.v) {\n case 1:\n case '1':\n case 'v1':\n protocolVersion = 'v1';\n break;\n case 'legacy':\n protocolVersion = 'legacy';\n break;\n default:\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_INVALID_PROTOCOL_VERSION, `Unknown/unsupported protocol version: ${jsonProperties.v}`);\n }\n }\n return ({\n protocol_version: protocolVersion\n });\n });\n}\n\nfunction getRandomAssociationPort() {\n return assertAssociationPort(49152 + Math.floor(Math.random() * (65535 - 49152 + 1)));\n}\nfunction assertAssociationPort(port) {\n if (port < 49152 || port > 65535) {\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE, `Association port number must be between 49152 and 65535. ${port} given.`, { port });\n }\n return port;\n}\n\n// https://stackoverflow.com/a/9458996/802047\nfunction arrayBufferToBase64String(buffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let ii = 0; ii < len; ii++) {\n binary += String.fromCharCode(bytes[ii]);\n }\n return window.btoa(binary);\n}\n\nfunction getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString) {\n return unsafeBase64EncodedString.replace(/[/+=]/g, (m) => ({\n '/': '_',\n '+': '-',\n '=': '.',\n }[m]));\n}\n\nconst INTENT_NAME = 'solana-wallet';\nfunction getPathParts(pathString) {\n return (pathString\n // Strip leading and trailing slashes\n .replace(/(^\\/+|\\/+$)/g, '')\n // Return an array of directories\n .split('/'));\n}\nfunction getIntentURL(methodPathname, intentUrlBase) {\n let baseUrl = null;\n if (intentUrlBase) {\n try {\n baseUrl = new URL(intentUrlBase);\n }\n catch (_a) { } // eslint-disable-line no-empty\n if ((baseUrl === null || baseUrl === void 0 ? void 0 : baseUrl.protocol) !== 'https:') {\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs');\n }\n }\n baseUrl || (baseUrl = new URL(`${INTENT_NAME}:/`));\n const pathname = methodPathname.startsWith('/')\n ? // Method is an absolute path. Replace it wholesale.\n methodPathname\n : // Method is a relative path. Merge it with the existing one.\n [...getPathParts(baseUrl.pathname), ...getPathParts(methodPathname)].join('/');\n return new URL(pathname, baseUrl);\n}\nfunction getAssociateAndroidIntentURL(associationPublicKey, putativePort, associationURLBase, protocolVersions = ['v1']) {\n return __awaiter(this, void 0, void 0, function* () {\n const associationPort = assertAssociationPort(putativePort);\n const exportedKey = yield crypto.subtle.exportKey('raw', associationPublicKey);\n const encodedKey = arrayBufferToBase64String(exportedKey);\n const url = getIntentURL('v1/associate/local', associationURLBase);\n url.searchParams.set('association', getStringWithURLUnsafeCharactersReplaced(encodedKey));\n url.searchParams.set('port', `${associationPort}`);\n protocolVersions.forEach((version) => {\n url.searchParams.set('v', version);\n });\n return url;\n });\n}\n\n// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/\nconst Browser = {\n Firefox: 0,\n Other: 1,\n};\nfunction assertUnreachable(x) {\n return x;\n}\nfunction getBrowser() {\n return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other;\n}\nfunction getDetectionPromise() {\n // Chrome and others silently fail if a custom protocol is not supported.\n // For these, we wait to see if the browser is navigated away from in\n // a reasonable amount of time (ie. the native wallet opened).\n return new Promise((resolve, reject) => {\n function cleanup() {\n clearTimeout(timeoutId);\n window.removeEventListener('blur', handleBlur);\n }\n function handleBlur() {\n cleanup();\n resolve();\n }\n window.addEventListener('blur', handleBlur);\n const timeoutId = setTimeout(() => {\n cleanup();\n reject();\n }, 2000);\n });\n}\nlet _frame = null;\nfunction launchUrlThroughHiddenFrame(url) {\n if (_frame == null) {\n _frame = document.createElement('iframe');\n _frame.style.display = 'none';\n document.body.appendChild(_frame);\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n _frame.contentWindow.location.href = url.toString();\n}\nfunction startSession(associationPublicKey, associationURLBase) {\n return __awaiter(this, void 0, void 0, function* () {\n const randomAssociationPort = getRandomAssociationPort();\n const associationUrl = yield getAssociateAndroidIntentURL(associationPublicKey, randomAssociationPort, associationURLBase);\n if (associationUrl.protocol === 'https:') {\n // The association URL is an Android 'App Link' or iOS 'Universal Link'.\n // These are regular web URLs that are designed to launch an app if it\n // is installed or load the actual target webpage if not.\n window.location.assign(associationUrl);\n }\n else {\n // The association URL has a custom protocol (eg. `solana-wallet:`)\n try {\n const browser = getBrowser();\n switch (browser) {\n case Browser.Firefox:\n // If a custom protocol is not supported in Firefox, it throws.\n launchUrlThroughHiddenFrame(associationUrl);\n // If we reached this line, it's supported.\n break;\n case Browser.Other: {\n const detectionPromise = getDetectionPromise();\n window.location.assign(associationUrl);\n yield detectionPromise;\n break;\n }\n default:\n assertUnreachable(browser);\n }\n }\n catch (e) {\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND, 'Found no installed wallet that supports the mobile wallet protocol.');\n }\n }\n return randomAssociationPort;\n });\n}\n\nconst WEBSOCKET_CONNECTION_CONFIG = {\n /**\n * 300 milliseconds is a generally accepted threshold for what someone\n * would consider an acceptable response time for a user interface\n * after having performed a low-attention tapping task. We set the initial\n * interval at which we wait for the wallet to set up the websocket at\n * half this, as per the Nyquist frequency, with a progressive backoff\n * sequence from there. The total wait time is 30s, which allows for the\n * user to be presented with a disambiguation dialog, select a wallet, and\n * for the wallet app to subsequently start.\n */\n retryDelayScheduleMs: [150, 150, 200, 500, 500, 750, 750, 1000],\n timeoutMs: 30000,\n};\nconst WEBSOCKET_PROTOCOL = 'com.solana.mobilewalletadapter.v1';\nfunction assertSecureContext() {\n if (typeof window === 'undefined' || window.isSecureContext !== true) {\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED, 'The mobile wallet adapter protocol must be used in a secure context (`https`).');\n }\n}\nfunction assertSecureEndpointSpecificURI(walletUriBase) {\n let url;\n try {\n url = new URL(walletUriBase);\n }\n catch (_a) {\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Invalid base URL supplied by wallet');\n }\n if (url.protocol !== 'https:') {\n throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs');\n }\n}\nfunction getSequenceNumberFromByteArray(byteArray) {\n const view = new DataView(byteArray);\n return view.getUint32(0, /* littleEndian */ false);\n}\nfunction transact(callback, config) {\n return __awaiter(this, void 0, void 0, function* () {\n assertSecureContext();\n const associationKeypair = yield generateAssociationKeypair();\n const sessionPort = yield startSession(associationKeypair.publicKey, config === null || config === void 0 ? void 0 : config.baseUri);\n const websocketURL = `ws://localhost:${sessionPort}/solana-wallet`;\n let connectionStartTime;\n const getNextRetryDelayMs = (() => {\n const schedule = [...WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs];\n return () => (schedule.length > 1 ? schedule.shift() : schedule[0]);\n })();\n let nextJsonRpcMessageId = 1;\n let lastKnownInboundSequenceNumber = 0;\n let state = { __type: 'disconnected' };\n return new Promise((resolve, reject) => {\n let socket;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const jsonRpcResponsePromises = {};\n const handleOpen = () => __awaiter(this, void 0, void 0, function* () {\n if (state.__type !== 'connecting') {\n console.warn('Expected adapter state to be `connecting` at the moment the websocket opens. ' +\n `Got \\`${state.__type}\\`.`);\n return;\n }\n const { associationKeypair } = state;\n socket.removeEventListener('open', handleOpen);\n const ecdhKeypair = yield generateECDHKeypair();\n socket.send(yield createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey));\n state = {\n __type: 'hello_req_sent',\n associationPublicKey: associationKeypair.publicKey,\n ecdhPrivateKey: ecdhKeypair.privateKey,\n };\n });\n const handleClose = (evt) => {\n if (evt.wasClean) {\n state = { __type: 'disconnected' };\n }\n else {\n reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, `The wallet session dropped unexpectedly (${evt.code}: ${evt.reason}).`, { closeEvent: evt }));\n }\n disposeSocket();\n };\n const handleError = (_evt) => __awaiter(this, void 0, void 0, function* () {\n disposeSocket();\n if (Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs) {\n reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, `Failed to connect to the wallet websocket on port ${sessionPort}.`));\n }\n else {\n yield new Promise((resolve) => {\n const retryDelayMs = getNextRetryDelayMs();\n retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs);\n });\n attemptSocketConnection();\n }\n });\n const handleMessage = (evt) => __awaiter(this, void 0, void 0, function* () {\n const responseBuffer = yield evt.data.arrayBuffer();\n switch (state.__type) {\n case 'connected':\n try {\n const sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES);\n const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);\n if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {\n throw new Error('Encrypted message has invalid sequence number');\n }\n lastKnownInboundSequenceNumber = sequenceNumber;\n const jsonRpcMessage = yield decryptJsonRpcMessage(responseBuffer, state.sharedSecret);\n const responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id];\n delete jsonRpcResponsePromises[jsonRpcMessage.id];\n responsePromise.resolve(jsonRpcMessage.result);\n }\n catch (e) {\n if (e instanceof SolanaMobileWalletAdapterProtocolError) {\n const responsePromise = jsonRpcResponsePromises[e.jsonRpcMessageId];\n delete jsonRpcResponsePromises[e.jsonRpcMessageId];\n responsePromise.reject(e);\n }\n else {\n throw e;\n }\n }\n break;\n case 'hello_req_sent': {\n const sharedSecret = yield parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey);\n const sessionPropertiesBuffer = responseBuffer.slice(ENCODED_PUBLIC_KEY_LENGTH_BYTES);\n const sessionProperties = sessionPropertiesBuffer.byteLength !== 0\n ? yield (() => __awaiter(this, void 0, void 0, function* () {\n const sequenceNumberVector = sessionPropertiesBuffer.slice(0, SEQUENCE_NUMBER_BYTES);\n const sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector);\n if (sequenceNumber !== (lastKnownInboundSequenceNumber + 1)) {\n throw new Error('Encrypted message has invalid sequence number');\n }\n lastKnownInboundSequenceNumber = sequenceNumber;\n return parseSessionProps(sessionPropertiesBuffer, sharedSecret);\n }))() : { protocol_version: 'legacy' };\n state = { __type: 'connected', sharedSecret, sessionProperties };\n const wallet = createMobileWalletProxy(sessionProperties.protocol_version, (method, params) => __awaiter(this, void 0, void 0, function* () {\n const id = nextJsonRpcMessageId++;\n socket.send(yield encryptJsonRpcMessage({\n id,\n jsonrpc: '2.0',\n method,\n params: params !== null && params !== void 0 ? params : {},\n }, sharedSecret));\n return new Promise((resolve, reject) => {\n jsonRpcResponsePromises[id] = {\n resolve(result) {\n switch (method) {\n case 'authorize':\n case 'reauthorize': {\n const { wallet_uri_base } = result;\n if (wallet_uri_base != null) {\n try {\n assertSecureEndpointSpecificURI(wallet_uri_base);\n }\n catch (e) {\n reject(e);\n return;\n }\n }\n break;\n }\n }\n resolve(result);\n },\n reject,\n };\n });\n }));\n try {\n resolve(yield callback(wallet));\n }\n catch (e) {\n reject(e);\n }\n finally {\n disposeSocket();\n socket.close();\n }\n break;\n }\n }\n });\n let disposeSocket;\n let retryWaitTimeoutId;\n const attemptSocketConnection = () => {\n if (disposeSocket) {\n disposeSocket();\n }\n state = { __type: 'connecting', associationKeypair };\n if (connectionStartTime === undefined) {\n connectionStartTime = Date.now();\n }\n socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]);\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('close', handleClose);\n socket.addEventListener('error', handleError);\n socket.addEventListener('message', handleMessage);\n disposeSocket = () => {\n window.clearTimeout(retryWaitTimeoutId);\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('close', handleClose);\n socket.removeEventListener('error', handleError);\n socket.removeEventListener('message', handleMessage);\n };\n };\n attemptSocketConnection();\n });\n });\n}\n\nexport { SolanaCloneAuthorization, SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode, SolanaMobileWalletAdapterProtocolError, SolanaMobileWalletAdapterProtocolErrorCode, SolanaSignInWithSolana, SolanaSignTransactions, transact };\n","import { VersionedMessage, Transaction, VersionedTransaction, SIGNATURE_LENGTH_IN_BYTES } from '@solana/web3.js';\nimport { transact as transact$1 } from '@solana-mobile/mobile-wallet-adapter-protocol';\nimport bs58 from 'bs58';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\n\nfunction fromUint8Array(byteArray) {\n return window.btoa(String.fromCharCode.call(null, ...byteArray));\n}\nfunction toUint8Array(base64EncodedByteArray) {\n return new Uint8Array(window\n .atob(base64EncodedByteArray)\n .split('')\n .map((c) => c.charCodeAt(0)));\n}\n\nfunction getPayloadFromTransaction(transaction) {\n const serializedTransaction = 'version' in transaction\n ? transaction.serialize()\n : transaction.serialize({\n requireAllSignatures: false,\n verifySignatures: false,\n });\n const payload = fromUint8Array(serializedTransaction);\n return payload;\n}\nfunction getTransactionFromWireMessage(byteArray) {\n const numSignatures = byteArray[0];\n const messageOffset = numSignatures * SIGNATURE_LENGTH_IN_BYTES + 1;\n const version = VersionedMessage.deserializeMessageVersion(byteArray.slice(messageOffset, byteArray.length));\n if (version === 'legacy') {\n return Transaction.from(byteArray);\n }\n else {\n return VersionedTransaction.deserialize(byteArray);\n }\n}\nfunction transact(callback, config) {\n return __awaiter(this, void 0, void 0, function* () {\n const augmentedCallback = (wallet) => {\n const augmentedAPI = new Proxy({}, {\n get(target, p) {\n if (target[p] == null) {\n switch (p) {\n case 'signAndSendTransactions':\n target[p] = function (_a) {\n var { minContextSlot, commitment, skipPreflight, maxRetries, waitForCommitmentToSendNextTransaction, transactions } = _a, rest = __rest(_a, [\"minContextSlot\", \"commitment\", \"skipPreflight\", \"maxRetries\", \"waitForCommitmentToSendNextTransaction\", \"transactions\"]);\n return __awaiter(this, void 0, void 0, function* () {\n const payloads = transactions.map(getPayloadFromTransaction);\n const options = {\n min_context_slot: minContextSlot,\n commitment: commitment,\n skip_preflight: skipPreflight,\n max_retries: maxRetries,\n wait_for_commitment_to_send_next_transaction: waitForCommitmentToSendNextTransaction\n };\n const { signatures: base64EncodedSignatures } = yield wallet.signAndSendTransactions(Object.assign(Object.assign(Object.assign({}, rest), (Object.values(options).some(element => element != null)\n ? { options: options }\n : null)), { payloads }));\n const signatures = base64EncodedSignatures.map(toUint8Array).map(bs58.encode);\n return signatures;\n });\n };\n break;\n case 'signMessages':\n target[p] = function (_a) {\n var { payloads } = _a, rest = __rest(_a, [\"payloads\"]);\n return __awaiter(this, void 0, void 0, function* () {\n const base64EncodedPayloads = payloads.map(fromUint8Array);\n const { signed_payloads: base64EncodedSignedMessages } = yield wallet.signMessages(Object.assign(Object.assign({}, rest), { payloads: base64EncodedPayloads }));\n const signedMessages = base64EncodedSignedMessages.map(toUint8Array);\n return signedMessages;\n });\n };\n break;\n case 'signTransactions':\n target[p] = function (_a) {\n var { transactions } = _a, rest = __rest(_a, [\"transactions\"]);\n return __awaiter(this, void 0, void 0, function* () {\n const payloads = transactions.map(getPayloadFromTransaction);\n const { signed_payloads: base64EncodedCompiledTransactions } = yield wallet.signTransactions(Object.assign(Object.assign({}, rest), { payloads }));\n const compiledTransactions = base64EncodedCompiledTransactions.map(toUint8Array);\n const signedTransactions = compiledTransactions.map(getTransactionFromWireMessage);\n return signedTransactions;\n });\n };\n break;\n default: {\n target[p] = wallet[p];\n break;\n }\n }\n }\n return target[p];\n },\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n });\n return callback(augmentedAPI);\n };\n return yield transact$1(augmentedCallback, config);\n });\n}\n\nexport { transact };\n","import { BaseSignInMessageSignerWalletAdapter, WalletReadyState, WalletPublicKeyError, WalletNotReadyError, WalletConnectionError, WalletDisconnectedError, WalletNotConnectedError, WalletSignTransactionError, WalletSendTransactionError, WalletSignMessageError } from '@solana/wallet-adapter-base';\nimport { PublicKey } from '@solana/web3.js';\nimport { transact } from '@solana-mobile/mobile-wallet-adapter-protocol-web3js';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\n\nfunction toUint8Array(base64EncodedByteArray) {\n return new Uint8Array(window\n .atob(base64EncodedByteArray)\n .split('')\n .map((c) => c.charCodeAt(0)));\n}\n\nfunction getIsSupported() {\n return (typeof window !== 'undefined' &&\n window.isSecureContext &&\n typeof document !== 'undefined' &&\n /android/i.test(navigator.userAgent));\n}\n\nconst SolanaMobileWalletAdapterWalletName = 'Mobile Wallet Adapter';\nconst SIGNATURE_LENGTH_IN_BYTES = 64;\nfunction getPublicKeyFromAddress(address) {\n const publicKeyByteArray = toUint8Array(address);\n return new PublicKey(publicKeyByteArray);\n}\nfunction isVersionedTransaction(transaction) {\n return 'version' in transaction;\n}\nclass SolanaMobileWalletAdapter extends BaseSignInMessageSignerWalletAdapter {\n constructor(config) {\n var _a;\n super();\n this.supportedTransactionVersions = new Set(\n // FIXME(#244): We can't actually know what versions are supported until we know which wallet we're talking to.\n ['legacy', 0]);\n this.name = SolanaMobileWalletAdapterWalletName;\n this.url = 'https://solanamobile.com/wallets';\n this.icon = 'data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiBoZWlnaHQ9IjI4IiB3aWR0aD0iMjgiIHZpZXdCb3g9Ii0zIDAgMjggMjgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0iI0RDQjhGRiI+PHBhdGggZD0iTTE3LjQgMTcuNEgxNXYyLjRoMi40di0yLjRabTEuMi05LjZoLTIuNHYyLjRoMi40VjcuOFoiLz48cGF0aCBkPSJNMjEuNiAzVjBoLTIuNHYzaC0zLjZWMGgtMi40djNoLTIuNHY2LjZINC41YTIuMSAyLjEgMCAxIDEgMC00LjJoMi43VjNINC41QTQuNSA0LjUgMCAwIDAgMCA3LjVWMjRoMjEuNnYtNi42aC0yLjR2NC4ySDIuNFYxMS41Yy41LjMgMS4yLjQgMS44LjVoNy41QTYuNiA2LjYgMCAwIDAgMjQgOVYzaC0yLjRabTAgNS43YTQuMiA0LjIgMCAxIDEtOC40IDBWNS40aDguNHYzLjNaIi8+PC9nPjwvc3ZnPg==';\n this._connecting = false;\n /**\n * Every time the connection is recycled in some way (eg. `disconnect()` is called)\n * increment this and use it to make sure that `transact` calls from the previous\n * 'generation' don't continue to do work and throw exceptions.\n */\n this._connectionGeneration = 0;\n this._readyState = getIsSupported() ? WalletReadyState.Loadable : WalletReadyState.Unsupported;\n this._authorizationResultCache = config.authorizationResultCache;\n this._addressSelector = config.addressSelector;\n this._appIdentity = config.appIdentity;\n this._chain = (_a = config.chain) !== null && _a !== void 0 ? _a : config.cluster;\n this._onWalletNotFound = config.onWalletNotFound;\n if (this._readyState !== WalletReadyState.Unsupported) {\n this._authorizationResultCache.get().then((authorizationResult) => {\n if (authorizationResult) {\n // Having a prior authorization result is, right now, the best\n // indication that a mobile wallet is installed. There is no API\n // we can use to test for whether the association URI is supported.\n this.declareWalletAsInstalled();\n }\n });\n }\n }\n get publicKey() {\n if (this._publicKey == null && this._selectedAddress != null) {\n try {\n this._publicKey = getPublicKeyFromAddress(this._selectedAddress);\n }\n catch (e) {\n throw new WalletPublicKeyError((e instanceof Error && (e === null || e === void 0 ? void 0 : e.message)) || 'Unknown error', e);\n }\n }\n return this._publicKey ? this._publicKey : null;\n }\n get connected() {\n return !!this._authorizationResult;\n }\n get connecting() {\n return this._connecting;\n }\n get readyState() {\n return this._readyState;\n }\n declareWalletAsInstalled() {\n if (this._readyState !== WalletReadyState.Installed) {\n this.emit('readyStateChange', (this._readyState = WalletReadyState.Installed));\n }\n }\n runWithGuard(callback) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n return yield callback();\n }\n catch (e) {\n this.emit('error', e);\n throw e;\n }\n });\n }\n /** @deprecated Use `autoConnect()` instead. */\n autoConnect_DO_NOT_USE_OR_YOU_WILL_BE_FIRED() {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.autoConnect();\n });\n }\n autoConnect() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.connecting || this.connected) {\n return;\n }\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n if (this._readyState !== WalletReadyState.Installed && this._readyState !== WalletReadyState.Loadable) {\n throw new WalletNotReadyError();\n }\n this._connecting = true;\n try {\n const cachedAuthorizationResult = yield this._authorizationResultCache.get();\n if (cachedAuthorizationResult) {\n // TODO: Evaluate whether there's any threat to not `awaiting` this expression\n this.handleAuthorizationResult(cachedAuthorizationResult);\n }\n }\n catch (e) {\n throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);\n }\n finally {\n this._connecting = false;\n }\n }));\n });\n }\n connect() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.connecting || this.connected) {\n return;\n }\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n if (this._readyState !== WalletReadyState.Installed && this._readyState !== WalletReadyState.Loadable) {\n throw new WalletNotReadyError();\n }\n this._connecting = true;\n try {\n yield this.performAuthorization();\n }\n catch (e) {\n throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);\n }\n finally {\n this._connecting = false;\n }\n }));\n });\n }\n performAuthorization(signInPayload) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const cachedAuthorizationResult = yield this._authorizationResultCache.get();\n if (cachedAuthorizationResult) {\n // TODO: Evaluate whether there's any threat to not `awaiting` this expression\n this.handleAuthorizationResult(cachedAuthorizationResult);\n return cachedAuthorizationResult;\n }\n return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {\n const authorizationResult = yield wallet.authorize({\n chain: this._chain,\n identity: this._appIdentity,\n sign_in_payload: signInPayload,\n });\n // TODO: Evaluate whether there's any threat to not `awaiting` this expression\n Promise.all([\n this._authorizationResultCache.set(authorizationResult),\n this.handleAuthorizationResult(authorizationResult),\n ]);\n return authorizationResult;\n }));\n }\n catch (e) {\n throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);\n }\n });\n }\n handleAuthorizationResult(authorizationResult) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const didPublicKeysChange = \n // Case 1: We started from having no authorization.\n this._authorizationResult == null ||\n // Case 2: The number of authorized accounts changed.\n ((_a = this._authorizationResult) === null || _a === void 0 ? void 0 : _a.accounts.length) !== authorizationResult.accounts.length ||\n // Case 3: The new list of addresses isn't exactly the same as the old list, in the same order.\n this._authorizationResult.accounts.some((account, ii) => account.address !== authorizationResult.accounts[ii].address);\n this._authorizationResult = authorizationResult;\n this.declareWalletAsInstalled();\n if (didPublicKeysChange) {\n const nextSelectedAddress = yield this._addressSelector.select(authorizationResult.accounts.map(({ address }) => address));\n if (nextSelectedAddress !== this._selectedAddress) {\n this._selectedAddress = nextSelectedAddress;\n delete this._publicKey;\n this.emit('connect', \n // Having just set `this._selectedAddress`, `this.publicKey` is definitely non-null\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.publicKey);\n }\n }\n });\n }\n performReauthorization(wallet, authToken) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const authorizationResult = yield wallet.authorize({\n auth_token: authToken,\n identity: this._appIdentity,\n });\n // TODO: Evaluate whether there's any threat to not `awaiting` this expression\n Promise.all([\n this._authorizationResultCache.set(authorizationResult),\n this.handleAuthorizationResult(authorizationResult),\n ]);\n }\n catch (e) {\n this.disconnect();\n throw new WalletDisconnectedError((e instanceof Error && (e === null || e === void 0 ? void 0 : e.message)) || 'Unknown error', e);\n }\n });\n }\n disconnect() {\n return __awaiter(this, void 0, void 0, function* () {\n this._authorizationResultCache.clear(); // TODO: Evaluate whether there's any threat to not `awaiting` this expression\n this._connecting = false;\n this._connectionGeneration++;\n delete this._authorizationResult;\n delete this._publicKey;\n delete this._selectedAddress;\n this.emit('disconnect');\n });\n }\n transact(callback) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n const walletUriBase = (_a = this._authorizationResult) === null || _a === void 0 ? void 0 : _a.wallet_uri_base;\n const config = walletUriBase ? { baseUri: walletUriBase } : undefined;\n const currentConnectionGeneration = this._connectionGeneration;\n try {\n return yield transact(callback, config);\n }\n catch (e) {\n if (this._connectionGeneration !== currentConnectionGeneration) {\n yield new Promise(() => { }); // Never resolve.\n }\n if (e instanceof Error &&\n e.name === 'SolanaMobileWalletAdapterError' &&\n e.code === 'ERROR_WALLET_NOT_FOUND') {\n yield this._onWalletNotFound(this);\n }\n throw e;\n }\n });\n }\n assertIsAuthorized() {\n if (!this._authorizationResult || !this._selectedAddress)\n throw new WalletNotConnectedError();\n return {\n authToken: this._authorizationResult.auth_token,\n selectedAddress: this._selectedAddress,\n };\n }\n performSignTransactions(transactions) {\n return __awaiter(this, void 0, void 0, function* () {\n const { authToken } = this.assertIsAuthorized();\n try {\n return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {\n yield this.performReauthorization(wallet, authToken);\n const signedTransactions = yield wallet.signTransactions({\n transactions,\n });\n return signedTransactions;\n }));\n }\n catch (error) {\n throw new WalletSignTransactionError(error === null || error === void 0 ? void 0 : error.message, error);\n }\n });\n }\n sendTransaction(transaction, connection, options) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n const { authToken } = this.assertIsAuthorized();\n const minContextSlot = options === null || options === void 0 ? void 0 : options.minContextSlot;\n try {\n return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {\n function getTargetCommitment() {\n let targetCommitment;\n switch (connection.commitment) {\n case 'confirmed':\n case 'finalized':\n case 'processed':\n targetCommitment = connection.commitment;\n break;\n default:\n targetCommitment = 'finalized';\n }\n let targetPreflightCommitment;\n switch (options === null || options === void 0 ? void 0 : options.preflightCommitment) {\n case 'confirmed':\n case 'finalized':\n case 'processed':\n targetPreflightCommitment = options.preflightCommitment;\n break;\n case undefined:\n targetPreflightCommitment = targetCommitment;\n break;\n default:\n targetPreflightCommitment = 'finalized';\n }\n const preflightCommitmentScore = targetPreflightCommitment === 'finalized'\n ? 2\n : targetPreflightCommitment === 'confirmed'\n ? 1\n : 0;\n const targetCommitmentScore = targetCommitment === 'finalized' ? 2 : targetCommitment === 'confirmed' ? 1 : 0;\n return preflightCommitmentScore < targetCommitmentScore\n ? targetPreflightCommitment\n : targetCommitment;\n }\n const [capabilities, _1, _2] = yield Promise.all([\n wallet.getCapabilities(),\n this.performReauthorization(wallet, authToken),\n isVersionedTransaction(transaction)\n ? null\n : /**\n * Unlike versioned transactions, legacy `Transaction` objects\n * may not have an associated `feePayer` or `recentBlockhash`.\n * This code exists to patch them up in case they are missing.\n */\n (() => __awaiter(this, void 0, void 0, function* () {\n var _a;\n transaction.feePayer || (transaction.feePayer = (_a = this.publicKey) !== null && _a !== void 0 ? _a : undefined);\n if (transaction.recentBlockhash == null) {\n const { blockhash } = yield connection.getLatestBlockhash({\n commitment: getTargetCommitment(),\n });\n transaction.recentBlockhash = blockhash;\n }\n }))(),\n ]);\n if (capabilities.supports_sign_and_send_transactions) {\n const signatures = yield wallet.signAndSendTransactions({\n minContextSlot,\n transactions: [transaction],\n });\n return signatures[0];\n }\n else {\n const [signedTransaction] = yield wallet.signTransactions({\n transactions: [transaction],\n });\n if (isVersionedTransaction(signedTransaction)) {\n return yield connection.sendTransaction(signedTransaction);\n }\n else {\n const serializedTransaction = signedTransaction.serialize();\n return yield connection.sendRawTransaction(serializedTransaction, Object.assign(Object.assign({}, options), { preflightCommitment: getTargetCommitment() }));\n }\n }\n }));\n }\n catch (error) {\n throw new WalletSendTransactionError(error === null || error === void 0 ? void 0 : error.message, error);\n }\n }));\n });\n }\n signTransaction(transaction) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n const [signedTransaction] = yield this.performSignTransactions([transaction]);\n return signedTransaction;\n }));\n });\n }\n signAllTransactions(transactions) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n const signedTransactions = yield this.performSignTransactions(transactions);\n return signedTransactions;\n }));\n });\n }\n signMessage(message) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n const { authToken, selectedAddress } = this.assertIsAuthorized();\n try {\n return yield this.transact((wallet) => __awaiter(this, void 0, void 0, function* () {\n yield this.performReauthorization(wallet, authToken);\n const [signedMessage] = yield wallet.signMessages({\n addresses: [selectedAddress],\n payloads: [message],\n });\n const signature = signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES);\n return signature;\n }));\n }\n catch (error) {\n throw new WalletSignMessageError(error === null || error === void 0 ? void 0 : error.message, error);\n }\n }));\n });\n }\n signIn(input) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield this.runWithGuard(() => __awaiter(this, void 0, void 0, function* () {\n var _a, _b;\n if (this._readyState !== WalletReadyState.Installed && this._readyState !== WalletReadyState.Loadable) {\n throw new WalletNotReadyError();\n }\n this._connecting = true;\n try {\n const authorizationResult = yield this.performAuthorization(Object.assign(Object.assign({}, input), { domain: (_a = input === null || input === void 0 ? void 0 : input.domain) !== null && _a !== void 0 ? _a : window.location.host }));\n if (!authorizationResult.sign_in_result) {\n throw new Error(\"Sign in failed, no sign in result returned by wallet\");\n }\n const signedInAddress = authorizationResult.sign_in_result.address;\n const signedInAccount = Object.assign(Object.assign({}, (_b = authorizationResult.accounts.find(acc => acc.address == signedInAddress)) !== null && _b !== void 0 ? _b : {\n address: signedInAddress\n }), { publicKey: toUint8Array(signedInAddress) });\n return {\n account: signedInAccount,\n signedMessage: toUint8Array(authorizationResult.sign_in_result.signed_message),\n signature: toUint8Array(authorizationResult.sign_in_result.signature)\n };\n }\n catch (e) {\n throw new WalletConnectionError((e instanceof Error && e.message) || 'Unknown error', e);\n }\n finally {\n this._connecting = false;\n }\n }));\n });\n }\n}\n\nfunction createDefaultAddressSelector() {\n return {\n select(addresses) {\n return __awaiter(this, void 0, void 0, function* () {\n return addresses[0];\n });\n },\n };\n}\n\nconst CACHE_KEY = 'SolanaMobileWalletAdapterDefaultAuthorizationCache';\nfunction createDefaultAuthorizationResultCache() {\n let storage;\n try {\n storage = window.localStorage;\n // eslint-disable-next-line no-empty\n }\n catch (_a) { }\n return {\n clear() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!storage) {\n return;\n }\n try {\n storage.removeItem(CACHE_KEY);\n // eslint-disable-next-line no-empty\n }\n catch (_a) { }\n });\n },\n get() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!storage) {\n return;\n }\n try {\n return JSON.parse(storage.getItem(CACHE_KEY)) || undefined;\n // eslint-disable-next-line no-empty\n }\n catch (_a) { }\n });\n },\n set(authorizationResult) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!storage) {\n return;\n }\n try {\n storage.setItem(CACHE_KEY, JSON.stringify(authorizationResult));\n // eslint-disable-next-line no-empty\n }\n catch (_a) { }\n });\n },\n };\n}\n\nfunction defaultWalletNotFoundHandler(mobileWalletAdapter) {\n return __awaiter(this, void 0, void 0, function* () {\n if (typeof window !== 'undefined') {\n window.location.assign(mobileWalletAdapter.url);\n }\n });\n}\nfunction createDefaultWalletNotFoundHandler() {\n return defaultWalletNotFoundHandler;\n}\n\nexport { SolanaMobileWalletAdapter, SolanaMobileWalletAdapterWalletName, createDefaultAddressSelector, createDefaultAuthorizationResultCache, createDefaultWalletNotFoundHandler };\n","import type { IdentifierString } from '@wallet-standard/base';\nimport type {\n SolanaSignTransactionInput,\n SolanaSignTransactionOptions,\n SolanaTransactionCommitment,\n SolanaTransactionVersion,\n} from './signTransaction.js';\n\n/** Name of the feature. */\nexport const SolanaSignAndSendTransaction = 'solana:signAndSendTransaction';\n\n/** TODO: docs */\nexport type SolanaSignAndSendTransactionFeature = {\n /** Name of the feature. */\n readonly [SolanaSignAndSendTransaction]: {\n /** Version of the feature API. */\n readonly version: SolanaSignAndSendTransactionVersion;\n\n /** TODO: docs */\n readonly supportedTransactionVersions: readonly SolanaTransactionVersion[];\n\n /**\n * Sign transactions using the account's secret key and send them to the chain.\n *\n * @param inputs Inputs for signing and sending transactions.\n *\n * @return Outputs of signing and sending transactions.\n */\n readonly signAndSendTransaction: SolanaSignAndSendTransactionMethod;\n };\n};\n\n/** Version of the feature. */\nexport type SolanaSignAndSendTransactionVersion = '1.0.0';\n\n/** TODO: docs */\nexport type SolanaSignAndSendTransactionMethod = (\n ...inputs: readonly SolanaSignAndSendTransactionInput[]\n) => Promise;\n\n/** Input for signing and sending a transaction. */\nexport interface SolanaSignAndSendTransactionInput extends SolanaSignTransactionInput {\n /** Chain to use. */\n readonly chain: IdentifierString;\n\n /** TODO: docs */\n readonly options?: SolanaSignAndSendTransactionOptions;\n}\n\n/** Output of signing and sending a transaction. */\nexport interface SolanaSignAndSendTransactionOutput {\n /** Transaction signature, as raw bytes. */\n readonly signature: Uint8Array;\n}\n\n/** Options for signing and sending a transaction. */\nexport type SolanaSignAndSendTransactionOptions = SolanaSignTransactionOptions & {\n /** Mode for signing and sending transactions. */\n readonly mode?: SolanaSignAndSendTransactionMode;\n\n /** Desired commitment level. If provided, confirm the transaction after sending. */\n readonly commitment?: SolanaTransactionCommitment;\n\n /** Disable transaction verification at the RPC. */\n readonly skipPreflight?: boolean;\n\n /** Maximum number of times for the RPC node to retry sending the transaction to the leader. */\n readonly maxRetries?: number;\n};\n\n/** Mode for signing and sending transactions. */\nexport type SolanaSignAndSendTransactionMode = 'parallel' | 'serial';\n","import type { IdentifierString, WalletAccount } from '@wallet-standard/base';\n\n/** Name of the feature. */\nexport const SolanaSignTransaction = 'solana:signTransaction';\n\n/** TODO: docs */\nexport type SolanaSignTransactionFeature = {\n /** Name of the feature. */\n readonly [SolanaSignTransaction]: {\n /** Version of the feature API. */\n readonly version: SolanaSignTransactionVersion;\n\n /** TODO: docs */\n readonly supportedTransactionVersions: readonly SolanaTransactionVersion[];\n\n /**\n * Sign transactions using the account's secret key.\n *\n * @param inputs Inputs for signing transactions.\n *\n * @return Outputs of signing transactions.\n */\n readonly signTransaction: SolanaSignTransactionMethod;\n };\n};\n\n/** Version of the feature. */\nexport type SolanaSignTransactionVersion = '1.0.0';\n\n/** TODO: docs */\nexport type SolanaTransactionVersion = 'legacy' | 0;\n\n/** TODO: docs */\nexport type SolanaSignTransactionMethod = (\n ...inputs: readonly SolanaSignTransactionInput[]\n) => Promise;\n\n/** Input for signing a transaction. */\nexport interface SolanaSignTransactionInput {\n /** Account to use. */\n readonly account: WalletAccount;\n\n /** Serialized transaction, as raw bytes. */\n readonly transaction: Uint8Array;\n\n /** Chain to use. */\n readonly chain?: IdentifierString;\n\n /** TODO: docs */\n readonly options?: SolanaSignTransactionOptions;\n}\n\n/** Output of signing a transaction. */\nexport interface SolanaSignTransactionOutput {\n /**\n * Signed, serialized transaction, as raw bytes.\n * Returning a transaction rather than signatures allows multisig wallets, program wallets, and other wallets that\n * use meta-transactions to return a modified, signed transaction.\n */\n readonly signedTransaction: Uint8Array;\n}\n\n/** Options for signing a transaction. */\nexport type SolanaSignTransactionOptions = {\n /** Preflight commitment level. */\n readonly preflightCommitment?: SolanaTransactionCommitment;\n\n /** The minimum slot that the request can be evaluated at. */\n readonly minContextSlot?: number;\n};\n\n/** Commitment level for transactions. */\nexport type SolanaTransactionCommitment = 'processed' | 'confirmed' | 'finalized';\n","import type { WalletAccount } from '@wallet-standard/base';\n\n/** Name of the feature. */\nexport const StandardConnect = 'standard:connect';\n/**\n * @deprecated Use {@link StandardConnect} instead.\n *\n * @group Deprecated\n */\nexport const Connect = StandardConnect;\n\n/**\n * `standard:connect` is a {@link \"@wallet-standard/base\".Wallet.features | feature} that may be implemented by a\n * {@link \"@wallet-standard/base\".Wallet} to allow the app to obtain authorization to use\n * {@link \"@wallet-standard/base\".Wallet.accounts}.\n *\n * @group Connect\n */\nexport type StandardConnectFeature = {\n /** Name of the feature. */\n readonly [StandardConnect]: {\n /** Version of the feature implemented by the Wallet. */\n readonly version: StandardConnectVersion;\n /** Method to call to use the feature. */\n readonly connect: StandardConnectMethod;\n };\n};\n/**\n * @deprecated Use {@link StandardConnectFeature} instead.\n *\n * @group Deprecated\n */\nexport type ConnectFeature = StandardConnectFeature;\n\n/**\n * Version of the {@link StandardConnectFeature} implemented by a {@link \"@wallet-standard/base\".Wallet}.\n *\n * @group Connect\n */\nexport type StandardConnectVersion = '1.0.0';\n/**\n * @deprecated Use {@link StandardConnectVersion} instead.\n *\n * @group Deprecated\n */\nexport type ConnectVersion = StandardConnectVersion;\n\n/**\n * Method to call to use the {@link StandardConnectFeature}.\n *\n * @group Connect\n */\nexport type StandardConnectMethod = (input?: StandardConnectInput) => Promise;\n/**\n * @deprecated Use {@link StandardConnectMethod} instead.\n *\n * @group Deprecated\n */\nexport type ConnectMethod = StandardConnectMethod;\n\n/**\n * Input for the {@link StandardConnectMethod}.\n *\n * @group Connect\n */\nexport interface StandardConnectInput {\n /**\n * By default, using the {@link StandardConnectFeature} should prompt the user to request authorization to accounts.\n * Set the `silent` flag to `true` to request accounts that have already been authorized without prompting.\n *\n * This flag may or may not be used by the Wallet and the app should not depend on it being used.\n * If this flag is used by the Wallet, the Wallet should not prompt the user, and should return only the accounts\n * that the app is authorized to use.\n */\n readonly silent?: boolean;\n}\n/**\n * @deprecated Use {@link StandardConnectInput} instead.\n *\n * @group Deprecated\n */\nexport type ConnectInput = StandardConnectInput;\n\n/**\n * Output of the {@link StandardConnectMethod}.\n *\n * @group Connect\n */\nexport interface StandardConnectOutput {\n /** List of accounts in the {@link \"@wallet-standard/base\".Wallet} that the app has been authorized to use. */\n readonly accounts: readonly WalletAccount[];\n}\n/**\n * @deprecated Use {@link StandardConnectOutput} instead.\n *\n * @group Deprecated\n */\nexport type ConnectOutput = StandardConnectOutput;\n","import type { Wallet } from '@wallet-standard/base';\n\n/** Name of the feature. */\nexport const StandardEvents = 'standard:events';\n/**\n * @deprecated Use {@link StandardEvents} instead.\n *\n * @group Deprecated\n */\nexport const Events = StandardEvents;\n\n/**\n * `standard:events` is a {@link \"@wallet-standard/base\".Wallet.features | feature} that may be implemented by a\n * {@link \"@wallet-standard/base\".Wallet} to allow the app to add an event listener and subscribe to events emitted by\n * the Wallet when properties of the Wallet {@link StandardEventsListeners.change}.\n *\n * @group Events\n */\nexport type StandardEventsFeature = {\n /** Name of the feature. */\n readonly [StandardEvents]: {\n /** Version of the feature implemented by the {@link \"@wallet-standard/base\".Wallet}. */\n readonly version: StandardEventsVersion;\n /** Method to call to use the feature. */\n readonly on: StandardEventsOnMethod;\n };\n};\n/**\n * @deprecated Use {@link StandardEventsFeature} instead.\n *\n * @group Deprecated\n */\nexport type EventsFeature = StandardEventsFeature;\n\n/**\n * Version of the {@link StandardEventsFeature} implemented by a {@link \"@wallet-standard/base\".Wallet}.\n *\n * @group Events\n */\nexport type StandardEventsVersion = '1.0.0';\n/**\n * @deprecated Use {@link StandardEventsVersion} instead.\n *\n * @group Deprecated\n */\nexport type EventsVersion = StandardEventsVersion;\n\n/**\n * Method to call to use the {@link StandardEventsFeature}.\n *\n * @param event Event type to listen for. {@link StandardEventsListeners.change | `change`} is the only event type.\n * @param listener Function that will be called when an event of the type is emitted.\n *\n * @return\n * `off` function which may be called to remove the event listener and unsubscribe from events.\n *\n * As with all event listeners, be careful to avoid memory leaks.\n *\n * @group Events\n */\nexport type StandardEventsOnMethod = (\n event: E,\n listener: StandardEventsListeners[E]\n) => () => void;\n/**\n * @deprecated Use {@link StandardEventsOnMethod} instead.\n *\n * @group Deprecated\n */\nexport type EventsOnMethod = StandardEventsOnMethod;\n\n/**\n * Types of event listeners of the {@link StandardEventsFeature}.\n *\n * @group Events\n */\nexport interface StandardEventsListeners {\n /**\n * Listener that will be called when {@link StandardEventsChangeProperties | properties} of the\n * {@link \"@wallet-standard/base\".Wallet} have changed.\n *\n * @param properties Properties that changed with their **new** values.\n */\n change(properties: StandardEventsChangeProperties): void;\n}\n/**\n * @deprecated Use {@link StandardEventsListeners} instead.\n *\n * @group Deprecated\n */\nexport type EventsListeners = StandardEventsListeners;\n\n/**\n * Names of {@link StandardEventsListeners} that can be listened for.\n *\n * @group Events\n */\nexport type StandardEventsNames = keyof StandardEventsListeners;\n/**\n * @deprecated Use {@link StandardEventsNames} instead.\n *\n * @group Deprecated\n */\nexport type EventsNames = StandardEventsNames;\n\n/**\n * Properties of a {@link \"@wallet-standard/base\".Wallet} that {@link StandardEventsListeners.change | changed} with their\n * **new** values.\n *\n * @group Events\n */\nexport interface StandardEventsChangeProperties {\n /**\n * {@link \"@wallet-standard/base\".Wallet.chains | Chains} supported by the Wallet.\n *\n * The Wallet should only define this field if the value of the property has changed.\n *\n * The value must be the **new** value of the property.\n */\n readonly chains?: Wallet['chains'];\n /**\n * {@link \"@wallet-standard/base\".Wallet.features | Features} supported by the Wallet.\n *\n * The Wallet should only define this field if the value of the property has changed.\n *\n * The value must be the **new** value of the property.\n */\n readonly features?: Wallet['features'];\n /**\n * {@link \"@wallet-standard/base\".Wallet.accounts | Accounts} that the app is authorized to use.\n *\n * The Wallet should only define this field if the value of the property has changed.\n *\n * The value must be the **new** value of the property.\n */\n readonly accounts?: Wallet['accounts'];\n}\n/**\n * @deprecated Use {@link StandardEventsChangeProperties} instead.\n *\n * @group Deprecated\n */\nexport type EventsChangeProperties = StandardEventsChangeProperties;\n","import {\n isWalletAdapterCompatibleStandardWallet,\n type StandardWalletAdapter,\n type WalletAdapterCompatibleStandardWallet,\n} from '@solana/wallet-adapter-base';\n\n/**\n * @deprecated Use `StandardWalletAdapter` from `@solana/wallet-adapter-base` instead.\n *\n * @group Deprecated\n */\nexport type StandardAdapter = StandardWalletAdapter;\n\n/**\n * @deprecated Use `WalletAdapterCompatibleStandardWallet` from `@solana/wallet-adapter-base` instead.\n *\n * @group Deprecated\n */\nexport type WalletAdapterCompatibleWallet = WalletAdapterCompatibleStandardWallet;\n\n/**\n * @deprecated Use `isWalletAdapterCompatibleStandardWallet` from `@solana/wallet-adapter-base` instead.\n *\n * @group Deprecated\n */\nexport const isWalletAdapterCompatibleWallet = isWalletAdapterCompatibleStandardWallet;\n","import {\n SolanaSignAndSendTransaction,\n type SolanaSignAndSendTransactionFeature,\n type SolanaSignInFeature,\n type SolanaSignMessageFeature,\n SolanaSignTransaction,\n type SolanaSignTransactionFeature,\n} from '@solana/wallet-standard-features';\nimport type { Wallet as StandardWallet, WalletWithFeatures as StandardWalletWithFeatures } from '@wallet-standard/base';\nimport {\n StandardConnect,\n type StandardConnectFeature,\n type StandardDisconnectFeature,\n StandardEvents,\n type StandardEventsFeature,\n} from '@wallet-standard/features';\nimport type { WalletAdapter, WalletAdapterProps } from './adapter.js';\n\nexport type WalletAdapterCompatibleStandardWallet = StandardWalletWithFeatures<\n StandardConnectFeature &\n StandardEventsFeature &\n (SolanaSignAndSendTransactionFeature | SolanaSignTransactionFeature) &\n (StandardDisconnectFeature | SolanaSignMessageFeature | SolanaSignInFeature | object)\n>;\n\nexport interface StandardWalletAdapterProps extends WalletAdapterProps {\n wallet: WalletAdapterCompatibleStandardWallet;\n standard: true;\n}\n\nexport type StandardWalletAdapter = WalletAdapter &\n StandardWalletAdapterProps;\n\nexport function isWalletAdapterCompatibleStandardWallet(\n wallet: StandardWallet\n): wallet is WalletAdapterCompatibleStandardWallet {\n return (\n StandardConnect in wallet.features &&\n StandardEvents in wallet.features &&\n (SolanaSignAndSendTransaction in wallet.features || SolanaSignTransaction in wallet.features)\n );\n}\n","import type { WalletAccount } from '@wallet-standard/base';\n\n/** Name of the feature. */\nexport const SolanaSignMessage = 'solana:signMessage';\n\n/** TODO: docs */\nexport type SolanaSignMessageFeature = {\n /** Name of the feature. */\n readonly [SolanaSignMessage]: {\n /** Version of the feature API. */\n readonly version: SolanaSignMessageVersion;\n\n /** Sign messages (arbitrary bytes) using the account's secret key. */\n readonly signMessage: SolanaSignMessageMethod;\n };\n};\n\n/** Version of the feature. */\nexport type SolanaSignMessageVersion = '1.1.0' | '1.0.0';\n\n/** TODO: docs */\nexport type SolanaSignMessageMethod = (\n ...inputs: readonly SolanaSignMessageInput[]\n) => Promise;\n\n/** Input for signing a message. */\nexport interface SolanaSignMessageInput {\n /** Account to use. */\n readonly account: WalletAccount;\n\n /** Message to sign, as raw bytes. */\n readonly message: Uint8Array;\n}\n\n/** Output of signing a message. */\nexport interface SolanaSignMessageOutput {\n /**\n * Message bytes that were signed.\n * The wallet may prefix or otherwise modify the message before signing it.\n */\n readonly signedMessage: Uint8Array;\n\n /**\n * Message signature produced.\n * If the signature type is provided, the signature must be Ed25519.\n */\n readonly signature: Uint8Array;\n\n /**\n * Optional type of the message signature produced.\n * If not provided, the signature must be Ed25519.\n */\n readonly signatureType?: 'ed25519';\n}\n","import type { WalletAccount } from '@wallet-standard/base';\n\n/** Name of the feature. */\nexport const SolanaSignIn = 'solana:signIn';\n\n/** TODO: docs */\nexport type SolanaSignInFeature = {\n /** Name of the feature. */\n readonly [SolanaSignIn]: {\n /** Version of the feature API. */\n readonly version: SolanaSignInVersion;\n\n /** Sign In With Solana (based on https://eips.ethereum.org/EIPS/eip-4361 and https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-122.md). */\n readonly signIn: SolanaSignInMethod;\n };\n};\n\n/** Version of the feature. */\nexport type SolanaSignInVersion = '1.0.0';\n\n/** TODO: docs */\nexport type SolanaSignInMethod = (...inputs: readonly SolanaSignInInput[]) => Promise;\n\n/** Input for signing in. */\nexport interface SolanaSignInInput {\n /**\n * Optional EIP-4361 Domain.\n * If not provided, the wallet must determine the Domain to include in the message.\n */\n readonly domain?: string;\n\n /**\n * Optional EIP-4361 Address.\n * If not provided, the wallet must determine the Address to include in the message.\n */\n readonly address?: string;\n\n /**\n * Optional EIP-4361 Statement.\n * If not provided, the wallet must not include Statement in the message.\n */\n readonly statement?: string;\n\n /**\n * Optional EIP-4361 URI.\n * If not provided, the wallet must not include URI in the message.\n */\n readonly uri?: string;\n\n /**\n * Optional EIP-4361 Version.\n * If not provided, the wallet must not include Version in the message.\n */\n readonly version?: string;\n\n /**\n * Optional EIP-4361 Chain ID.\n * If not provided, the wallet must not include Chain ID in the message.\n */\n readonly chainId?: string;\n\n /**\n * Optional EIP-4361 Nonce.\n * If not provided, the wallet must not include Nonce in the message.\n */\n readonly nonce?: string;\n\n /**\n * Optional EIP-4361 Issued At.\n * If not provided, the wallet must not include Issued At in the message.\n */\n readonly issuedAt?: string;\n\n /**\n * Optional EIP-4361 Expiration Time.\n * If not provided, the wallet must not include Expiration Time in the message.\n */\n readonly expirationTime?: string;\n\n /**\n * Optional EIP-4361 Not Before.\n * If not provided, the wallet must not include Not Before in the message.\n */\n readonly notBefore?: string;\n\n /**\n * Optional EIP-4361 Request ID.\n * If not provided, the wallet must not include Request ID in the message.\n */\n readonly requestId?: string;\n\n /**\n * Optional EIP-4361 Resources.\n * If not provided, the wallet must not include Resources in the message.\n */\n readonly resources?: readonly string[];\n}\n\n/** Output of signing in. */\nexport interface SolanaSignInOutput {\n /**\n * Account that was signed in.\n * The address of the account may be different from the provided input Address.\n */\n readonly account: WalletAccount;\n\n /**\n * Message bytes that were signed.\n * The wallet may prefix or otherwise modify the message before signing it.\n */\n readonly signedMessage: Uint8Array;\n\n /**\n * Message signature produced.\n * If the signature type is provided, the signature must be Ed25519.\n */\n readonly signature: Uint8Array;\n\n /**\n * Optional type of the message signature produced.\n * If not provided, the signature must be Ed25519.\n */\n readonly signatureType?: 'ed25519';\n}\n","import type { IdentifierString } from '@wallet-standard/base';\n\n/** Solana Mainnet (beta) cluster, e.g. https://api.mainnet-beta.solana.com */\nexport const SOLANA_MAINNET_CHAIN = 'solana:mainnet';\n\n/** Solana Devnet cluster, e.g. https://api.devnet.solana.com */\nexport const SOLANA_DEVNET_CHAIN = 'solana:devnet';\n\n/** Solana Testnet cluster, e.g. https://api.testnet.solana.com */\nexport const SOLANA_TESTNET_CHAIN = 'solana:testnet';\n\n/** Solana Localnet cluster, e.g. http://localhost:8899 */\nexport const SOLANA_LOCALNET_CHAIN = 'solana:localnet';\n\n/** Array of all Solana clusters */\nexport const SOLANA_CHAINS = [\n SOLANA_MAINNET_CHAIN,\n SOLANA_DEVNET_CHAIN,\n SOLANA_TESTNET_CHAIN,\n SOLANA_LOCALNET_CHAIN,\n] as const;\n\n/** Type of all Solana clusters */\nexport type SolanaChain = (typeof SOLANA_CHAINS)[number];\n\n/**\n * Check if a chain corresponds with one of the Solana clusters.\n */\nexport function isSolanaChain(chain: IdentifierString): chain is SolanaChain {\n return SOLANA_CHAINS.includes(chain as SolanaChain);\n}\n","import type { SolanaChain } from '@solana/wallet-standard-chains';\nimport {\n SOLANA_DEVNET_CHAIN,\n SOLANA_LOCALNET_CHAIN,\n SOLANA_MAINNET_CHAIN,\n SOLANA_TESTNET_CHAIN,\n} from '@solana/wallet-standard-chains';\n\n/** TODO: docs */\nexport const MAINNET_ENDPOINT = 'https://api.mainnet-beta.solana.com';\n/** TODO: docs */\nexport const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';\n/** TODO: docs */\nexport const TESTNET_ENDPOINT = 'https://api.testnet.solana.com';\n/** TODO: docs */\nexport const LOCALNET_ENDPOINT = 'http://localhost:8899';\n\n/**\n * TODO: docs\n */\nexport function getChainForEndpoint(endpoint: string): SolanaChain {\n if (endpoint.includes(MAINNET_ENDPOINT)) return SOLANA_MAINNET_CHAIN;\n if (/\\bdevnet\\b/i.test(endpoint)) return SOLANA_DEVNET_CHAIN;\n if (/\\btestnet\\b/i.test(endpoint)) return SOLANA_TESTNET_CHAIN;\n if (/\\blocalhost\\b/i.test(endpoint) || /\\b127\\.0\\.0\\.1\\b/.test(endpoint)) return SOLANA_LOCALNET_CHAIN;\n return SOLANA_MAINNET_CHAIN;\n}\n\n/**\n * TODO: docs\n */\nexport function getEndpointForChain(chain: SolanaChain, endpoint?: string): string {\n if (endpoint) return endpoint;\n if (chain === SOLANA_MAINNET_CHAIN) return MAINNET_ENDPOINT;\n if (chain === SOLANA_DEVNET_CHAIN) return DEVNET_ENDPOINT;\n if (chain === SOLANA_TESTNET_CHAIN) return TESTNET_ENDPOINT;\n if (chain === SOLANA_LOCALNET_CHAIN) return LOCALNET_ENDPOINT;\n return MAINNET_ENDPOINT;\n}\n","import type { SolanaTransactionCommitment } from '@solana/wallet-standard-features';\n\n// Copied from @solana/web3.js\ntype Commitment = 'processed' | 'confirmed' | 'finalized' | 'recent' | 'single' | 'singleGossip' | 'root' | 'max';\n\n/**\n * TODO: docs\n */\nexport function getCommitment(commitment?: Commitment): SolanaTransactionCommitment | undefined {\n switch (commitment) {\n case 'processed':\n case 'confirmed':\n case 'finalized':\n case undefined:\n return commitment;\n case 'recent':\n return 'processed';\n case 'single':\n case 'singleGossip':\n return 'confirmed';\n case 'max':\n case 'root':\n return 'finalized';\n default:\n return undefined;\n }\n}\n","/** Name of the feature. */\nexport const StandardDisconnect = 'standard:disconnect';\n/**\n * @deprecated Use {@link StandardDisconnect} instead.\n *\n * @group Deprecated\n */\nexport const Disconnect = StandardDisconnect;\n\n/**\n * `standard:disconnect` is a {@link \"@wallet-standard/base\".Wallet.features | feature} that may be implemented by a\n * {@link \"@wallet-standard/base\".Wallet} to allow the app to perform any cleanup work.\n *\n * This feature may or may not be used by the app and the Wallet should not depend on it being used.\n * If this feature is used by the app, the Wallet should perform any cleanup work, but should not revoke authorization\n * to use accounts previously granted through the {@link ConnectFeature}.\n *\n * @group Disconnect\n */\nexport type StandardDisconnectFeature = {\n /** Name of the feature. */\n readonly [StandardDisconnect]: {\n /** Version of the feature implemented by the Wallet. */\n readonly version: StandardDisconnectVersion;\n /** Method to call to use the feature. */\n readonly disconnect: StandardDisconnectMethod;\n };\n};\n/**\n * @deprecated Use {@link StandardDisconnectFeature} instead.\n *\n * @group Deprecated\n */\nexport type DisconnectFeature = StandardDisconnectFeature;\n\n/**\n * Version of the {@link StandardDisconnectFeature} implemented by a Wallet.\n *\n * @group Disconnect\n */\nexport type StandardDisconnectVersion = '1.0.0';\n/**\n * @deprecated Use {@link StandardDisconnectVersion} instead.\n *\n * @group Deprecated\n */\nexport type DisconnectVersion = StandardDisconnectVersion;\n\n/**\n * Method to call to use the {@link StandardDisconnectFeature}.\n *\n * @group Disconnect\n */\nexport type StandardDisconnectMethod = () => Promise;\n/**\n * @deprecated Use {@link StandardDisconnectMethod} instead.\n *\n * @group Deprecated\n */\nexport type DisconnectMethod = StandardDisconnectMethod;\n","import type { WalletAccount } from '@wallet-standard/base';\n\n/**\n * Base implementation of a {@link \"@wallet-standard/base\".WalletAccount} to be used or extended by a\n * {@link \"@wallet-standard/base\".Wallet}.\n *\n * `WalletAccount` properties must be read-only. This class enforces this by making all properties\n * [truly private](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields) and\n * read-only, using getters for access, returning copies instead of references, and calling\n * [Object.freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)\n * on the instance.\n *\n * @group Account\n */\nexport class ReadonlyWalletAccount implements WalletAccount {\n readonly #address: WalletAccount['address'];\n readonly #publicKey: WalletAccount['publicKey'];\n readonly #chains: WalletAccount['chains'];\n readonly #features: WalletAccount['features'];\n readonly #label: WalletAccount['label'];\n readonly #icon: WalletAccount['icon'];\n\n /** Implementation of {@link \"@wallet-standard/base\".WalletAccount.address | WalletAccount::address} */\n get address() {\n return this.#address;\n }\n\n /** Implementation of {@link \"@wallet-standard/base\".WalletAccount.publicKey | WalletAccount::publicKey} */\n get publicKey() {\n return this.#publicKey.slice();\n }\n\n /** Implementation of {@link \"@wallet-standard/base\".WalletAccount.chains | WalletAccount::chains} */\n get chains() {\n return this.#chains.slice();\n }\n\n /** Implementation of {@link \"@wallet-standard/base\".WalletAccount.features | WalletAccount::features} */\n get features() {\n return this.#features.slice();\n }\n\n /** Implementation of {@link \"@wallet-standard/base\".WalletAccount.label | WalletAccount::label} */\n get label() {\n return this.#label;\n }\n\n /** Implementation of {@link \"@wallet-standard/base\".WalletAccount.icon | WalletAccount::icon} */\n get icon() {\n return this.#icon;\n }\n\n /**\n * Create and freeze a read-only account.\n *\n * @param account Account to copy properties from.\n */\n constructor(account: WalletAccount) {\n if (new.target === ReadonlyWalletAccount) {\n Object.freeze(this);\n }\n\n this.#address = account.address;\n this.#publicKey = account.publicKey.slice();\n this.#chains = account.chains.slice();\n this.#features = account.features.slice();\n this.#label = account.label;\n this.#icon = account.icon;\n }\n}\n\n/**\n * Efficiently compare {@link Indexed} arrays (e.g. `Array` and `Uint8Array`).\n *\n * @param a An array.\n * @param b Another array.\n *\n * @return `true` if the arrays have the same length and elements, `false` otherwise.\n *\n * @group Util\n */\nexport function arraysEqual(a: Indexed, b: Indexed): boolean {\n if (a === b) return true;\n\n const length = a.length;\n if (length !== b.length) return false;\n\n for (let i = 0; i < length; i++) {\n if (a[i] !== b[i]) return false;\n }\n\n return true;\n}\n\n/**\n * Efficiently compare byte arrays, using {@link arraysEqual}.\n *\n * @param a A byte array.\n * @param b Another byte array.\n *\n * @return `true` if the byte arrays have the same length and bytes, `false` otherwise.\n *\n * @group Util\n */\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return arraysEqual(a, b);\n}\n\n/**\n * Efficiently concatenate byte arrays without modifying them.\n *\n * @param first A byte array.\n * @param others Additional byte arrays.\n *\n * @return New byte array containing the concatenation of all the byte arrays.\n *\n * @group Util\n */\nexport function concatBytes(first: Uint8Array, ...others: Uint8Array[]): Uint8Array {\n const length = others.reduce((length, bytes) => length + bytes.length, first.length);\n const bytes = new Uint8Array(length);\n\n bytes.set(first, 0);\n for (const other of others) {\n bytes.set(other, bytes.length);\n }\n\n return bytes;\n}\n\n/**\n * Create a new object with a subset of fields from a source object.\n *\n * @param source Object to pick fields from.\n * @param keys Names of fields to pick.\n *\n * @return New object with only the picked fields.\n *\n * @group Util\n */\nexport function pick(source: T, ...keys: K[]): Pick {\n const picked = {} as Pick;\n for (const key of keys) {\n picked[key] = source[key];\n }\n return picked;\n}\n\n/**\n * Call a callback function, catch an error if it throws, and log the error without rethrowing.\n *\n * @param callback Function to call.\n *\n * @group Util\n */\nexport function guard(callback: () => void) {\n try {\n callback();\n } catch (error) {\n console.error(error);\n }\n}\n\n/**\n * @internal\n *\n * Type with a numeric `length` and numerically indexed elements of a generic type `T`.\n *\n * For example, `Array` and `Uint8Array`.\n *\n * @group Internal\n */\nexport interface Indexed {\n length: number;\n [index: number]: T;\n}\n","import {\n BaseWalletAdapter,\n isVersionedTransaction,\n type SendTransactionOptions,\n type StandardWalletAdapter as StandardWalletAdapterType,\n type SupportedTransactionVersions,\n WalletAccountError,\n type WalletAdapterCompatibleStandardWallet,\n WalletConfigError,\n WalletConnectionError,\n WalletDisconnectedError,\n WalletDisconnectionError,\n WalletError,\n type WalletName,\n WalletNotConnectedError,\n WalletNotReadyError,\n WalletPublicKeyError,\n WalletReadyState,\n WalletSendTransactionError,\n WalletSignInError,\n WalletSignMessageError,\n WalletSignTransactionError,\n} from '@solana/wallet-adapter-base';\nimport {\n SolanaSignAndSendTransaction,\n type SolanaSignAndSendTransactionFeature,\n SolanaSignIn,\n type SolanaSignInInput,\n type SolanaSignInOutput,\n SolanaSignMessage,\n SolanaSignTransaction,\n type SolanaSignTransactionFeature,\n} from '@solana/wallet-standard-features';\nimport { getChainForEndpoint, getCommitment } from '@solana/wallet-standard-util';\nimport type { Connection, TransactionSignature } from '@solana/web3.js';\nimport { PublicKey, Transaction, VersionedTransaction } from '@solana/web3.js';\nimport type { WalletAccount } from '@wallet-standard/base';\nimport {\n StandardConnect,\n type StandardConnectInput,\n StandardDisconnect,\n StandardEvents,\n type StandardEventsListeners,\n} from '@wallet-standard/features';\nimport { arraysEqual } from '@wallet-standard/wallet';\nimport bs58 from 'bs58';\n\n/** TODO: docs */\nexport interface StandardWalletAdapterConfig {\n wallet: WalletAdapterCompatibleStandardWallet;\n}\n\n/** TODO: docs */\nexport class StandardWalletAdapter extends BaseWalletAdapter implements StandardWalletAdapterType {\n #account: WalletAccount | null;\n #publicKey: PublicKey | null;\n #connecting: boolean;\n #disconnecting: boolean;\n #off: (() => void) | null;\n #supportedTransactionVersions: SupportedTransactionVersions;\n readonly #wallet: WalletAdapterCompatibleStandardWallet;\n readonly #readyState: WalletReadyState =\n typeof window === 'undefined' || typeof document === 'undefined'\n ? WalletReadyState.Unsupported\n : WalletReadyState.Installed;\n\n get name() {\n return this.#wallet.name as WalletName;\n }\n\n get url() {\n return 'https://github.com/solana-labs/wallet-standard';\n }\n\n get icon() {\n return this.#wallet.icon;\n }\n\n get readyState() {\n return this.#readyState;\n }\n\n get publicKey() {\n return this.#publicKey;\n }\n\n get connecting() {\n return this.#connecting;\n }\n\n get supportedTransactionVersions() {\n return this.#supportedTransactionVersions;\n }\n\n get wallet(): WalletAdapterCompatibleStandardWallet {\n return this.#wallet;\n }\n\n get standard() {\n return true as const;\n }\n\n constructor({ wallet }: StandardWalletAdapterConfig) {\n super();\n\n this.#wallet = wallet;\n this.#account = null;\n this.#publicKey = null;\n this.#connecting = false;\n this.#disconnecting = false;\n this.#off = this.#wallet.features[StandardEvents].on('change', this.#changed);\n\n this.#reset();\n }\n\n destroy(): void {\n this.#account = null;\n this.#publicKey = null;\n this.#connecting = false;\n this.#disconnecting = false;\n\n const off = this.#off;\n if (off) {\n this.#off = null;\n off();\n }\n }\n\n async autoConnect(): Promise {\n return this.#connect({ silent: true });\n }\n\n async connect(): Promise {\n return this.#connect();\n }\n\n async #connect(input?: StandardConnectInput): Promise {\n try {\n if (this.connected || this.connecting) return;\n if (this.#readyState !== WalletReadyState.Installed) throw new WalletNotReadyError();\n\n this.#connecting = true;\n\n if (!this.#wallet.accounts.length) {\n try {\n await this.#wallet.features[StandardConnect].connect(input);\n } catch (error: any) {\n throw new WalletConnectionError(error?.message, error);\n }\n }\n\n const account = this.#wallet.accounts[0];\n if (!account) throw new WalletAccountError();\n\n this.#connected(account);\n } catch (error: any) {\n this.emit('error', error);\n throw error;\n } finally {\n this.#connecting = false;\n }\n }\n\n async disconnect(): Promise {\n if (StandardDisconnect in this.#wallet.features) {\n try {\n this.#disconnecting = true;\n await this.#wallet.features[StandardDisconnect].disconnect();\n } catch (error: any) {\n this.emit('error', new WalletDisconnectionError(error?.message, error));\n } finally {\n this.#disconnecting = false;\n }\n }\n\n this.#disconnected();\n }\n\n #connected(account: WalletAccount) {\n let publicKey: PublicKey;\n try {\n // Use account.address instead of account.publicKey since address could be a PDA\n publicKey = new PublicKey(account.address);\n } catch (error: any) {\n throw new WalletPublicKeyError(error?.message, error);\n }\n\n this.#account = account;\n this.#publicKey = publicKey;\n this.#reset();\n this.emit('connect', publicKey);\n }\n\n #disconnected(): void {\n this.#account = null;\n this.#publicKey = null;\n this.#reset();\n this.emit('disconnect');\n }\n\n #reset() {\n const supportedTransactionVersions =\n SolanaSignAndSendTransaction in this.#wallet.features\n ? this.#wallet.features[SolanaSignAndSendTransaction].supportedTransactionVersions\n : this.#wallet.features[SolanaSignTransaction].supportedTransactionVersions;\n this.#supportedTransactionVersions = arraysEqual(supportedTransactionVersions, ['legacy'])\n ? null\n : new Set(supportedTransactionVersions);\n\n if (SolanaSignTransaction in this.#wallet.features && this.#account?.features.includes(SolanaSignTransaction)) {\n this.signTransaction = this.#signTransaction;\n this.signAllTransactions = this.#signAllTransactions;\n } else {\n delete this.signTransaction;\n delete this.signAllTransactions;\n }\n\n if (SolanaSignMessage in this.#wallet.features && this.#account?.features.includes(SolanaSignMessage)) {\n this.signMessage = this.#signMessage;\n } else {\n delete this.signMessage;\n }\n\n if (SolanaSignIn in this.#wallet.features) {\n this.signIn = this.#signIn;\n } else {\n delete this.signIn;\n }\n }\n\n #changed: StandardEventsListeners['change'] = (properties) => {\n // If accounts have changed on the wallet, reflect this on the adapter.\n if ('accounts' in properties) {\n const account = this.#wallet.accounts[0];\n // If the adapter isn't connected, or is disconnecting, or the first account hasn't changed, do nothing.\n if (this.#account && !this.#disconnecting && account !== this.#account) {\n // If there's a connected account, connect the adapter. Otherwise, disconnect it.\n if (account) {\n // Connect the adapter.\n this.#connected(account);\n } else {\n // Emit an error because the wallet spontaneously disconnected.\n this.emit('error', new WalletDisconnectedError());\n // Disconnect the adapter.\n this.#disconnected();\n }\n }\n }\n\n // After reflecting account changes, if features have changed on the wallet, reflect this on the adapter.\n if ('features' in properties) {\n this.#reset();\n }\n };\n\n async sendTransaction(\n transaction: T,\n connection: Connection,\n options: SendTransactionOptions = {}\n ): Promise {\n try {\n const account = this.#account;\n if (!account) throw new WalletNotConnectedError();\n\n let feature: typeof SolanaSignAndSendTransaction | typeof SolanaSignTransaction;\n if (SolanaSignAndSendTransaction in this.#wallet.features) {\n if (account.features.includes(SolanaSignAndSendTransaction)) {\n feature = SolanaSignAndSendTransaction;\n } else if (\n SolanaSignTransaction in this.#wallet.features &&\n account.features.includes(SolanaSignTransaction)\n ) {\n feature = SolanaSignTransaction;\n } else {\n throw new WalletAccountError();\n }\n } else if (SolanaSignTransaction in this.#wallet.features) {\n if (!account.features.includes(SolanaSignTransaction)) throw new WalletAccountError();\n feature = SolanaSignTransaction;\n } else {\n throw new WalletConfigError();\n }\n\n const chain = getChainForEndpoint(connection.rpcEndpoint);\n if (!account.chains.includes(chain)) throw new WalletSendTransactionError();\n\n try {\n const { signers, ...sendOptions } = options;\n\n let serializedTransaction: Uint8Array;\n if (isVersionedTransaction(transaction)) {\n signers?.length && transaction.sign(signers);\n serializedTransaction = transaction.serialize();\n } else {\n transaction = (await this.prepareTransaction(transaction, connection, sendOptions)) as T;\n signers?.length && (transaction as Transaction).partialSign(...signers);\n serializedTransaction = new Uint8Array(\n (transaction as Transaction).serialize({\n requireAllSignatures: false,\n verifySignatures: false,\n })\n );\n }\n\n if (feature === SolanaSignAndSendTransaction) {\n const [output] = await (this.#wallet.features as SolanaSignAndSendTransactionFeature)[\n SolanaSignAndSendTransaction\n ].signAndSendTransaction({\n account,\n chain,\n transaction: serializedTransaction,\n options: {\n preflightCommitment: getCommitment(\n sendOptions.preflightCommitment || connection.commitment\n ),\n skipPreflight: sendOptions.skipPreflight,\n maxRetries: sendOptions.maxRetries,\n minContextSlot: sendOptions.minContextSlot,\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return bs58.encode(output!.signature);\n } else {\n const [output] = await (this.#wallet.features as SolanaSignTransactionFeature)[\n SolanaSignTransaction\n ].signTransaction({\n account,\n chain,\n transaction: serializedTransaction,\n options: {\n preflightCommitment: getCommitment(\n sendOptions.preflightCommitment || connection.commitment\n ),\n minContextSlot: sendOptions.minContextSlot,\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return await connection.sendRawTransaction(output!.signedTransaction, {\n ...sendOptions,\n preflightCommitment: getCommitment(sendOptions.preflightCommitment || connection.commitment),\n });\n }\n } catch (error: any) {\n if (error instanceof WalletError) throw error;\n throw new WalletSendTransactionError(error?.message, error);\n }\n } catch (error: any) {\n this.emit('error', error);\n throw error;\n }\n }\n\n signTransaction: ((transaction: T) => Promise) | undefined;\n async #signTransaction(transaction: T): Promise {\n try {\n const account = this.#account;\n if (!account) throw new WalletNotConnectedError();\n\n if (!(SolanaSignTransaction in this.#wallet.features)) throw new WalletConfigError();\n if (!account.features.includes(SolanaSignTransaction)) throw new WalletAccountError();\n\n try {\n const signedTransactions = await this.#wallet.features[SolanaSignTransaction].signTransaction({\n account,\n transaction: isVersionedTransaction(transaction)\n ? transaction.serialize()\n : new Uint8Array(\n transaction.serialize({\n requireAllSignatures: false,\n verifySignatures: false,\n })\n ),\n });\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const serializedTransaction = signedTransactions[0]!.signedTransaction;\n\n return (\n isVersionedTransaction(transaction)\n ? VersionedTransaction.deserialize(serializedTransaction)\n : Transaction.from(serializedTransaction)\n ) as T;\n } catch (error: any) {\n if (error instanceof WalletError) throw error;\n throw new WalletSignTransactionError(error?.message, error);\n }\n } catch (error: any) {\n this.emit('error', error);\n throw error;\n }\n }\n\n signAllTransactions: ((transaction: T[]) => Promise) | undefined;\n async #signAllTransactions(transactions: T[]): Promise {\n try {\n const account = this.#account;\n if (!account) throw new WalletNotConnectedError();\n\n if (!(SolanaSignTransaction in this.#wallet.features)) throw new WalletConfigError();\n if (!account.features.includes(SolanaSignTransaction)) throw new WalletAccountError();\n\n try {\n const signedTransactions = await this.#wallet.features[SolanaSignTransaction].signTransaction(\n ...transactions.map((transaction) => ({\n account,\n transaction: isVersionedTransaction(transaction)\n ? transaction.serialize()\n : new Uint8Array(\n transaction.serialize({\n requireAllSignatures: false,\n verifySignatures: false,\n })\n ),\n }))\n );\n\n return transactions.map((transaction, index) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const signedTransaction = signedTransactions[index]!.signedTransaction;\n\n return (\n isVersionedTransaction(transaction)\n ? VersionedTransaction.deserialize(signedTransaction)\n : Transaction.from(signedTransaction)\n ) as T;\n });\n } catch (error: any) {\n throw new WalletSignTransactionError(error?.message, error);\n }\n } catch (error: any) {\n this.emit('error', error);\n throw error;\n }\n }\n\n signMessage: ((message: Uint8Array) => Promise) | undefined;\n async #signMessage(message: Uint8Array): Promise {\n try {\n const account = this.#account;\n if (!account) throw new WalletNotConnectedError();\n\n if (!(SolanaSignMessage in this.#wallet.features)) throw new WalletConfigError();\n if (!account.features.includes(SolanaSignMessage)) throw new WalletAccountError();\n\n try {\n const signedMessages = await this.#wallet.features[SolanaSignMessage].signMessage({\n account,\n message,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return signedMessages[0]!.signature;\n } catch (error: any) {\n throw new WalletSignMessageError(error?.message, error);\n }\n } catch (error: any) {\n this.emit('error', error);\n throw error;\n }\n }\n\n signIn: ((input?: SolanaSignInInput) => Promise) | undefined;\n async #signIn(input: SolanaSignInInput = {}): Promise {\n try {\n if (!(SolanaSignIn in this.#wallet.features)) throw new WalletConfigError();\n\n let output: SolanaSignInOutput | undefined;\n try {\n [output] = await this.#wallet.features[SolanaSignIn].signIn(input);\n } catch (error: any) {\n throw new WalletSignInError(error?.message, error);\n }\n\n if (!output) throw new WalletSignInError();\n this.#connected(output.account);\n return output;\n } catch (error: any) {\n this.emit('error', error);\n throw error;\n }\n }\n}\n","import type {\n DEPRECATED_WalletsCallback,\n DEPRECATED_WalletsWindow,\n Wallet,\n WalletEventsWindow,\n WindowAppReadyEvent,\n WindowAppReadyEventAPI,\n} from '@wallet-standard/base';\n\nlet wallets: Wallets | undefined = undefined;\nconst registered = new Set();\nconst listeners: { [E in WalletsEventNames]?: WalletsEventsListeners[E][] } = {};\n\n/**\n * Get an API for {@link Wallets.get | getting}, {@link Wallets.on | listening for}, and\n * {@link Wallets.register | registering} {@link \"@wallet-standard/base\".Wallet | Wallets}.\n *\n * When called for the first time --\n *\n * This dispatches a {@link \"@wallet-standard/base\".WindowAppReadyEvent} to notify each Wallet that the app is ready\n * to register it.\n *\n * This also adds a listener for {@link \"@wallet-standard/base\".WindowRegisterWalletEvent} to listen for a notification\n * from each Wallet that the Wallet is ready to be registered by the app.\n *\n * This combination of event dispatch and listener guarantees that each Wallet will be registered synchronously as soon\n * as the app is ready whether the app loads before or after each Wallet.\n *\n * @return API for getting, listening for, and registering Wallets.\n *\n * @group App\n */\nexport function getWallets(): Wallets {\n if (wallets) return wallets;\n wallets = Object.freeze({ register, get, on });\n if (typeof window === 'undefined') return wallets;\n\n const api = Object.freeze({ register });\n try {\n (window as WalletEventsWindow).addEventListener('wallet-standard:register-wallet', ({ detail: callback }) =>\n callback(api)\n );\n } catch (error) {\n console.error('wallet-standard:register-wallet event listener could not be added\\n', error);\n }\n try {\n (window as WalletEventsWindow).dispatchEvent(new AppReadyEvent(api));\n } catch (error) {\n console.error('wallet-standard:app-ready event could not be dispatched\\n', error);\n }\n\n return wallets;\n}\n\n/**\n * API for {@link Wallets.get | getting}, {@link Wallets.on | listening for}, and\n * {@link Wallets.register | registering} {@link \"@wallet-standard/base\".Wallet | Wallets}.\n *\n * @group App\n */\nexport interface Wallets {\n /**\n * Get all Wallets that have been registered.\n *\n * @return Registered Wallets.\n */\n get(): readonly Wallet[];\n\n /**\n * Add an event listener and subscribe to events for Wallets that are\n * {@link WalletsEventsListeners.register | registered} and\n * {@link WalletsEventsListeners.unregister | unregistered}.\n *\n * @param event Event type to listen for. {@link WalletsEventsListeners.register | `register`} and\n * {@link WalletsEventsListeners.unregister | `unregister`} are the only event types.\n * @param listener Function that will be called when an event of the type is emitted.\n *\n * @return\n * `off` function which may be called to remove the event listener and unsubscribe from events.\n *\n * As with all event listeners, be careful to avoid memory leaks.\n */\n on(event: E, listener: WalletsEventsListeners[E]): () => void;\n\n /**\n * Register Wallets. This can be used to programmatically wrap non-standard wallets as Standard Wallets.\n *\n * Apps generally do not need to, and should not, call this.\n *\n * @param wallets Wallets to register.\n *\n * @return\n * `unregister` function which may be called to programmatically unregister the registered Wallets.\n *\n * Apps generally do not need to, and should not, call this.\n */\n register(...wallets: Wallet[]): () => void;\n}\n\n/**\n * Types of event listeners of the {@link Wallets} API.\n *\n * @group App\n */\nexport interface WalletsEventsListeners {\n /**\n * Emitted when Wallets are registered.\n *\n * @param wallets Wallets that were registered.\n */\n register(...wallets: Wallet[]): void;\n\n /**\n * Emitted when Wallets are unregistered.\n *\n * @param wallets Wallets that were unregistered.\n */\n unregister(...wallets: Wallet[]): void;\n}\n\n/**\n * Names of {@link WalletsEventsListeners} that can be listened for.\n *\n * @group App\n */\nexport type WalletsEventNames = keyof WalletsEventsListeners;\n\n/**\n * @deprecated Use {@link WalletsEventsListeners} instead.\n *\n * @group Deprecated\n */\nexport type WalletsEvents = WalletsEventsListeners;\n\nfunction register(...wallets: Wallet[]): () => void {\n // Filter out wallets that have already been registered.\n // This prevents the same wallet from being registered twice, but it also prevents wallets from being\n // unregistered by reusing a reference to the wallet to obtain the unregister function for it.\n wallets = wallets.filter((wallet) => !registered.has(wallet));\n // If there are no new wallets to register, just return a no-op unregister function.\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n if (!wallets.length) return () => {};\n\n wallets.forEach((wallet) => registered.add(wallet));\n listeners['register']?.forEach((listener) => guard(() => listener(...wallets)));\n // Return a function that unregisters the registered wallets.\n return function unregister(): void {\n wallets.forEach((wallet) => registered.delete(wallet));\n listeners['unregister']?.forEach((listener) => guard(() => listener(...wallets)));\n };\n}\n\nfunction get(): readonly Wallet[] {\n return [...registered];\n}\n\nfunction on(event: E, listener: WalletsEventsListeners[E]): () => void {\n listeners[event]?.push(listener) || (listeners[event] = [listener]);\n // Return a function that removes the event listener.\n return function off(): void {\n listeners[event] = listeners[event]?.filter((existingListener) => listener !== existingListener);\n };\n}\n\nfunction guard(callback: () => void) {\n try {\n callback();\n } catch (error) {\n console.error(error);\n }\n}\n\nclass AppReadyEvent extends Event implements WindowAppReadyEvent {\n readonly #detail: WindowAppReadyEventAPI;\n\n get detail() {\n return this.#detail;\n }\n\n get type() {\n return 'wallet-standard:app-ready' as const;\n }\n\n constructor(api: WindowAppReadyEventAPI) {\n super('wallet-standard:app-ready', {\n bubbles: false,\n cancelable: false,\n composed: false,\n });\n this.#detail = api;\n }\n\n /** @deprecated */\n preventDefault(): never {\n throw new Error('preventDefault cannot be called');\n }\n\n /** @deprecated */\n stopImmediatePropagation(): never {\n throw new Error('stopImmediatePropagation cannot be called');\n }\n\n /** @deprecated */\n stopPropagation(): never {\n throw new Error('stopPropagation cannot be called');\n }\n}\n\n/**\n * @deprecated Use {@link getWallets} instead.\n *\n * @group Deprecated\n */\nexport function DEPRECATED_getWallets(): Wallets {\n if (wallets) return wallets;\n wallets = getWallets();\n if (typeof window === 'undefined') return wallets;\n\n const callbacks = (window as DEPRECATED_WalletsWindow).navigator.wallets || [];\n if (!Array.isArray(callbacks)) {\n console.error('window.navigator.wallets is not an array');\n return wallets;\n }\n\n const { register } = wallets;\n const push = (...callbacks: DEPRECATED_WalletsCallback[]): void =>\n callbacks.forEach((callback) => guard(() => callback({ register })));\n try {\n Object.defineProperty((window as DEPRECATED_WalletsWindow).navigator, 'wallets', {\n value: Object.freeze({ push }),\n });\n } catch (error) {\n console.error('window.navigator.wallets could not be set');\n return wallets;\n }\n\n push(...callbacks);\n return wallets;\n}\n","import type { Adapter, WalletName } from '@solana/wallet-adapter-base';\nimport { isWalletAdapterCompatibleWallet, StandardWalletAdapter } from '@solana/wallet-standard-wallet-adapter-base';\nimport { DEPRECATED_getWallets } from '@wallet-standard/app';\nimport type { Wallet } from '@wallet-standard/base';\nimport { useEffect, useMemo, useRef, useState } from 'react';\n\nexport function useStandardWalletAdapters(adapters: Adapter[]): Adapter[] {\n const warnings = useConstant(() => new Set());\n const { get, on } = useConstant(() => DEPRECATED_getWallets());\n const [standardAdapters, setStandardAdapters] = useState(() => wrapWalletsWithAdapters(get()));\n\n useEffect(() => {\n const listeners = [\n on('register', (...wallets) =>\n setStandardAdapters((standardAdapters) => [...standardAdapters, ...wrapWalletsWithAdapters(wallets)])\n ),\n on('unregister', (...wallets) =>\n setStandardAdapters((standardAdapters) =>\n standardAdapters.filter((standardAdapter) =>\n wallets.some((wallet) => wallet === standardAdapter.wallet)\n )\n )\n ),\n ];\n return () => listeners.forEach((off) => off());\n }, [on]);\n\n const prevStandardAdapters = usePrevious(standardAdapters);\n useEffect(() => {\n if (!prevStandardAdapters) return;\n\n const currentAdapters = new Set(standardAdapters);\n const removedAdapters = new Set(\n prevStandardAdapters.filter((previousAdapter) => !currentAdapters.has(previousAdapter))\n );\n removedAdapters.forEach((adapter) => adapter.destroy());\n }, [prevStandardAdapters, standardAdapters]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(() => () => standardAdapters.forEach((adapter) => adapter.destroy()), []);\n\n return useMemo(\n () => [\n ...standardAdapters,\n ...adapters.filter(({ name }) => {\n if (standardAdapters.some((standardAdapter) => standardAdapter.name === name)) {\n if (!warnings.has(name)) {\n warnings.add(name);\n console.warn(\n `${name} was registered as a Standard Wallet. The Wallet Adapter for ${name} can be removed from your app.`\n );\n }\n return false;\n }\n return true;\n }),\n ],\n [standardAdapters, adapters, warnings]\n );\n}\n\nfunction useConstant(fn: () => T): T {\n const ref = useRef<{ value: T }>();\n if (!ref.current) {\n ref.current = { value: fn() };\n }\n return ref.current.value;\n}\n\nfunction usePrevious(state: T): T | undefined {\n const ref = useRef();\n useEffect(() => {\n ref.current = state;\n });\n return ref.current;\n}\n\nfunction wrapWalletsWithAdapters(wallets: readonly Wallet[]): readonly StandardWalletAdapter[] {\n return wallets.filter(isWalletAdapterCompatibleWallet).map((wallet) => new StandardWalletAdapter({ wallet }));\n}\n","import { SolanaMobileWalletAdapterWalletName } from '@solana-mobile/wallet-adapter-mobile';\nimport { type Adapter, WalletReadyState } from '@solana/wallet-adapter-base';\n\nexport enum Environment {\n DESKTOP_WEB,\n MOBILE_WEB,\n}\n\ntype Config = Readonly<{\n adapters: Adapter[];\n userAgentString: string | null;\n}>;\n\nfunction isWebView(userAgentString: string) {\n return /(WebView|Version\\/.+(Chrome)\\/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)|; wv\\).+(Chrome)\\/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+))/i.test(\n userAgentString\n );\n}\n\nexport default function getEnvironment({ adapters, userAgentString }: Config): Environment {\n if (\n adapters.some(\n (adapter) =>\n adapter.name !== SolanaMobileWalletAdapterWalletName &&\n adapter.readyState === WalletReadyState.Installed\n )\n ) {\n /**\n * There are only two ways a browser extension adapter should be able to reach `Installed` status:\n *\n * 1. Its browser extension is installed.\n * 2. The app is running on a mobile wallet's in-app browser.\n *\n * In either case, we consider the environment to be desktop-like.\n */\n return Environment.DESKTOP_WEB;\n }\n if (\n userAgentString &&\n // Step 1: Check whether we're on a platform that supports MWA at all.\n /android/i.test(userAgentString) &&\n // Step 2: Determine that we are *not* running in a WebView.\n !isWebView(userAgentString)\n ) {\n return Environment.MOBILE_WEB;\n } else {\n return Environment.DESKTOP_WEB;\n }\n}\n","import { type Cluster } from '@solana/web3.js';\n\nexport default function getInferredClusterFromEndpoint(endpoint?: string): Cluster {\n if (!endpoint) {\n return 'mainnet-beta';\n }\n if (/devnet/i.test(endpoint)) {\n return 'devnet';\n } else if (/testnet/i.test(endpoint)) {\n return 'testnet';\n } else {\n return 'mainnet-beta';\n }\n}\n","import { WalletError } from '@solana/wallet-adapter-base';\n\nexport class WalletNotSelectedError extends WalletError {\n name = 'WalletNotSelectedError';\n}\n","import {\n type Adapter,\n type MessageSignerWalletAdapterProps,\n type SignerWalletAdapterProps,\n type SignInMessageSignerWalletAdapterProps,\n type WalletAdapterProps,\n type WalletError,\n type WalletName,\n WalletNotConnectedError,\n WalletNotReadyError,\n WalletReadyState,\n} from '@solana/wallet-adapter-base';\nimport { type PublicKey } from '@solana/web3.js';\nimport React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { WalletNotSelectedError } from './errors.js';\nimport { WalletContext } from './useWallet.js';\n\nexport interface WalletProviderBaseProps {\n children: ReactNode;\n wallets: Adapter[];\n adapter: Adapter | null;\n isUnloadingRef: React.RefObject;\n // NOTE: The presence/absence of this handler implies that auto-connect is enabled/disabled.\n onAutoConnectRequest?: () => Promise;\n onConnectError: () => void;\n onError?: (error: WalletError, adapter?: Adapter) => void;\n onSelectWallet: (walletName: WalletName | null) => void;\n}\n\nexport function WalletProviderBase({\n children,\n wallets: adapters,\n adapter,\n isUnloadingRef,\n onAutoConnectRequest,\n onConnectError,\n onError,\n onSelectWallet,\n}: WalletProviderBaseProps) {\n const isConnectingRef = useRef(false);\n const [connecting, setConnecting] = useState(false);\n const isDisconnectingRef = useRef(false);\n const [disconnecting, setDisconnecting] = useState(false);\n const [publicKey, setPublicKey] = useState(() => adapter?.publicKey ?? null);\n const [connected, setConnected] = useState(() => adapter?.connected ?? false);\n\n /**\n * Store the error handlers as refs so that a change in the\n * custom error handler does not recompute other dependencies.\n */\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n return () => {\n onErrorRef.current = undefined;\n };\n }, [onError]);\n const handleErrorRef = useRef((error: WalletError, adapter?: Adapter) => {\n if (!isUnloadingRef.current) {\n if (onErrorRef.current) {\n onErrorRef.current(error, adapter);\n } else {\n console.error(error, adapter);\n if (error instanceof WalletNotReadyError && typeof window !== 'undefined' && adapter) {\n window.open(adapter.url, '_blank');\n }\n }\n }\n return error;\n });\n\n // Wrap adapters to conform to the `Wallet` interface\n const [wallets, setWallets] = useState(() =>\n adapters\n .map((adapter) => ({\n adapter,\n readyState: adapter.readyState,\n }))\n .filter(({ readyState }) => readyState !== WalletReadyState.Unsupported)\n );\n\n // When the adapters change, start to listen for changes to their `readyState`\n useEffect(() => {\n // When the adapters change, wrap them to conform to the `Wallet` interface\n setWallets((wallets) =>\n adapters\n .map((adapter, index) => {\n const wallet = wallets[index];\n // If the wallet hasn't changed, return the same instance\n return wallet && wallet.adapter === adapter && wallet.readyState === adapter.readyState\n ? wallet\n : {\n adapter: adapter,\n readyState: adapter.readyState,\n };\n })\n .filter(({ readyState }) => readyState !== WalletReadyState.Unsupported)\n );\n function handleReadyStateChange(this: Adapter, readyState: WalletReadyState) {\n setWallets((prevWallets) => {\n const index = prevWallets.findIndex(({ adapter }) => adapter === this);\n if (index === -1) return prevWallets;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { adapter } = prevWallets[index]!;\n return [\n ...prevWallets.slice(0, index),\n { adapter, readyState },\n ...prevWallets.slice(index + 1),\n ].filter(({ readyState }) => readyState !== WalletReadyState.Unsupported);\n });\n }\n adapters.forEach((adapter) => adapter.on('readyStateChange', handleReadyStateChange, adapter));\n return () => {\n adapters.forEach((adapter) => adapter.off('readyStateChange', handleReadyStateChange, adapter));\n };\n }, [adapter, adapters]);\n\n const wallet = useMemo(() => wallets.find((wallet) => wallet.adapter === adapter) ?? null, [adapter, wallets]);\n\n // Setup and teardown event listeners when the adapter changes\n useEffect(() => {\n if (!adapter) return;\n\n const handleConnect = (publicKey: PublicKey) => {\n setPublicKey(publicKey);\n isConnectingRef.current = false;\n setConnecting(false);\n setConnected(true);\n isDisconnectingRef.current = false;\n setDisconnecting(false);\n };\n\n const handleDisconnect = () => {\n if (isUnloadingRef.current) return;\n\n setPublicKey(null);\n isConnectingRef.current = false;\n setConnecting(false);\n setConnected(false);\n isDisconnectingRef.current = false;\n setDisconnecting(false);\n };\n\n const handleError = (error: WalletError) => {\n handleErrorRef.current(error, adapter);\n };\n\n adapter.on('connect', handleConnect);\n adapter.on('disconnect', handleDisconnect);\n adapter.on('error', handleError);\n\n return () => {\n adapter.off('connect', handleConnect);\n adapter.off('disconnect', handleDisconnect);\n adapter.off('error', handleError);\n\n handleDisconnect();\n };\n }, [adapter, isUnloadingRef]);\n\n // When the adapter changes, clear the `autoConnect` tracking flag\n const didAttemptAutoConnectRef = useRef(false);\n useEffect(() => {\n return () => {\n didAttemptAutoConnectRef.current = false;\n };\n }, [adapter]);\n\n // If auto-connect is enabled, request to connect when the adapter changes and is ready\n useEffect(() => {\n if (\n didAttemptAutoConnectRef.current ||\n isConnectingRef.current ||\n connected ||\n !onAutoConnectRequest ||\n !(wallet?.readyState === WalletReadyState.Installed || wallet?.readyState === WalletReadyState.Loadable)\n )\n return;\n\n isConnectingRef.current = true;\n setConnecting(true);\n didAttemptAutoConnectRef.current = true;\n (async function () {\n try {\n await onAutoConnectRequest();\n } catch {\n onConnectError();\n // Drop the error. It will be caught by `handleError` anyway.\n } finally {\n setConnecting(false);\n isConnectingRef.current = false;\n }\n })();\n }, [connected, onAutoConnectRequest, onConnectError, wallet]);\n\n // Send a transaction using the provided connection\n const sendTransaction: WalletAdapterProps['sendTransaction'] = useCallback(\n async (transaction, connection, options) => {\n if (!adapter) throw handleErrorRef.current(new WalletNotSelectedError());\n if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter);\n return await adapter.sendTransaction(transaction, connection, options);\n },\n [adapter, connected]\n );\n\n // Sign a transaction if the wallet supports it\n const signTransaction: SignerWalletAdapterProps['signTransaction'] | undefined = useMemo(\n () =>\n adapter && 'signTransaction' in adapter\n ? async (transaction) => {\n if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter);\n return await adapter.signTransaction(transaction);\n }\n : undefined,\n [adapter, connected]\n );\n\n // Sign multiple transactions if the wallet supports it\n const signAllTransactions: SignerWalletAdapterProps['signAllTransactions'] | undefined = useMemo(\n () =>\n adapter && 'signAllTransactions' in adapter\n ? async (transactions) => {\n if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter);\n return await adapter.signAllTransactions(transactions);\n }\n : undefined,\n [adapter, connected]\n );\n\n // Sign an arbitrary message if the wallet supports it\n const signMessage: MessageSignerWalletAdapterProps['signMessage'] | undefined = useMemo(\n () =>\n adapter && 'signMessage' in adapter\n ? async (message) => {\n if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter);\n return await adapter.signMessage(message);\n }\n : undefined,\n [adapter, connected]\n );\n\n // Sign in if the wallet supports it\n const signIn: SignInMessageSignerWalletAdapterProps['signIn'] | undefined = useMemo(\n () =>\n adapter && 'signIn' in adapter\n ? async (input) => {\n return await adapter.signIn(input);\n }\n : undefined,\n [adapter]\n );\n\n const handleConnect = useCallback(async () => {\n if (isConnectingRef.current || isDisconnectingRef.current || wallet?.adapter.connected) return;\n if (!wallet) throw handleErrorRef.current(new WalletNotSelectedError());\n const { adapter, readyState } = wallet;\n if (!(readyState === WalletReadyState.Installed || readyState === WalletReadyState.Loadable))\n throw handleErrorRef.current(new WalletNotReadyError(), adapter);\n isConnectingRef.current = true;\n setConnecting(true);\n try {\n await adapter.connect();\n } catch (e) {\n onConnectError();\n throw e;\n } finally {\n setConnecting(false);\n isConnectingRef.current = false;\n }\n }, [onConnectError, wallet]);\n\n const handleDisconnect = useCallback(async () => {\n if (isDisconnectingRef.current) return;\n if (!adapter) return;\n isDisconnectingRef.current = true;\n setDisconnecting(true);\n try {\n await adapter.disconnect();\n } finally {\n setDisconnecting(false);\n isDisconnectingRef.current = false;\n }\n }, [adapter]);\n\n return (\n \n {children}\n \n );\n}\n","import {\n createDefaultAddressSelector,\n createDefaultAuthorizationResultCache,\n createDefaultWalletNotFoundHandler,\n SolanaMobileWalletAdapter,\n SolanaMobileWalletAdapterWalletName,\n} from '@solana-mobile/wallet-adapter-mobile';\nimport { type Adapter, type WalletError, type WalletName } from '@solana/wallet-adapter-base';\nimport { useStandardWalletAdapters } from '@solana/wallet-standard-wallet-adapter-react';\nimport React, { type ReactNode, useCallback, useEffect, useMemo, useRef } from 'react';\nimport getEnvironment, { Environment } from './getEnvironment.js';\nimport getInferredClusterFromEndpoint from './getInferredClusterFromEndpoint.js';\nimport { useConnection } from './useConnection.js';\nimport { useLocalStorage } from './useLocalStorage.js';\nimport { WalletProviderBase } from './WalletProviderBase.js';\n\nexport interface WalletProviderProps {\n children: ReactNode;\n wallets: Adapter[];\n autoConnect?: boolean | ((adapter: Adapter) => Promise);\n localStorageKey?: string;\n onError?: (error: WalletError, adapter?: Adapter) => void;\n}\n\nlet _userAgent: string | null;\nfunction getUserAgent() {\n if (_userAgent === undefined) {\n _userAgent = globalThis.navigator?.userAgent ?? null;\n }\n return _userAgent;\n}\n\nfunction getIsMobile(adapters: Adapter[]) {\n const userAgentString = getUserAgent();\n return getEnvironment({ adapters, userAgentString }) === Environment.MOBILE_WEB;\n}\n\nfunction getUriForAppIdentity() {\n const location = globalThis.location;\n if (!location) return;\n return `${location.protocol}//${location.host}`;\n}\n\nexport function WalletProvider({\n children,\n wallets: adapters,\n autoConnect,\n localStorageKey = 'walletName',\n onError,\n}: WalletProviderProps) {\n const { connection } = useConnection();\n const adaptersWithStandardAdapters = useStandardWalletAdapters(adapters);\n const mobileWalletAdapter = useMemo(() => {\n if (!getIsMobile(adaptersWithStandardAdapters)) {\n return null;\n }\n const existingMobileWalletAdapter = adaptersWithStandardAdapters.find(\n (adapter) => adapter.name === SolanaMobileWalletAdapterWalletName\n );\n if (existingMobileWalletAdapter) {\n return existingMobileWalletAdapter;\n }\n return new SolanaMobileWalletAdapter({\n addressSelector: createDefaultAddressSelector(),\n appIdentity: {\n uri: getUriForAppIdentity(),\n },\n authorizationResultCache: createDefaultAuthorizationResultCache(),\n cluster: getInferredClusterFromEndpoint(connection?.rpcEndpoint),\n onWalletNotFound: createDefaultWalletNotFoundHandler(),\n });\n }, [adaptersWithStandardAdapters, connection?.rpcEndpoint]);\n const adaptersWithMobileWalletAdapter = useMemo(() => {\n if (mobileWalletAdapter == null || adaptersWithStandardAdapters.indexOf(mobileWalletAdapter) !== -1) {\n return adaptersWithStandardAdapters;\n }\n return [mobileWalletAdapter, ...adaptersWithStandardAdapters];\n }, [adaptersWithStandardAdapters, mobileWalletAdapter]);\n const [walletName, setWalletName] = useLocalStorage(\n localStorageKey,\n getIsMobile(adaptersWithStandardAdapters) ? SolanaMobileWalletAdapterWalletName : null\n );\n const adapter = useMemo(\n () => adaptersWithMobileWalletAdapter.find((a) => a.name === walletName) ?? null,\n [adaptersWithMobileWalletAdapter, walletName]\n );\n const changeWallet = useCallback(\n (nextWalletName: WalletName | null) => {\n if (walletName === nextWalletName) return;\n if (\n adapter &&\n // Selecting a wallet other than the mobile wallet adapter is not\n // sufficient reason to call `disconnect` on the mobile wallet adapter.\n // Calling `disconnect` on the mobile wallet adapter causes the entire\n // authorization store to be wiped.\n adapter.name !== SolanaMobileWalletAdapterWalletName\n ) {\n adapter.disconnect();\n }\n setWalletName(nextWalletName);\n },\n [adapter, setWalletName, walletName]\n );\n useEffect(() => {\n if (!adapter) return;\n function handleDisconnect() {\n if (isUnloadingRef.current) return;\n // Leave the adapter selected in the event of a disconnection.\n if (walletName === SolanaMobileWalletAdapterWalletName && getIsMobile(adaptersWithStandardAdapters)) return;\n setWalletName(null);\n }\n adapter.on('disconnect', handleDisconnect);\n return () => {\n adapter.off('disconnect', handleDisconnect);\n };\n }, [adapter, adaptersWithStandardAdapters, setWalletName, walletName]);\n const hasUserSelectedAWallet = useRef(false);\n const handleAutoConnectRequest = useMemo(() => {\n if (!autoConnect || !adapter) return;\n return async () => {\n // If autoConnect is true or returns true, use the default autoConnect behavior.\n if (autoConnect === true || (await autoConnect(adapter))) {\n if (hasUserSelectedAWallet.current) {\n await adapter.connect();\n } else {\n await adapter.autoConnect();\n }\n }\n };\n }, [autoConnect, adapter]);\n const isUnloadingRef = useRef(false);\n useEffect(() => {\n if (walletName === SolanaMobileWalletAdapterWalletName && getIsMobile(adaptersWithStandardAdapters)) {\n isUnloadingRef.current = false;\n return;\n }\n function handleBeforeUnload() {\n isUnloadingRef.current = true;\n }\n /**\n * Some wallets fire disconnection events when the window unloads. Since there's no way to\n * distinguish between a disconnection event received because a user initiated it, and one\n * that was received because they've closed the window, we have to track window unload\n * events themselves. Downstream components use this information to decide whether to act\n * upon or drop wallet events and errors.\n */\n window.addEventListener('beforeunload', handleBeforeUnload);\n return () => {\n window.removeEventListener('beforeunload', handleBeforeUnload);\n };\n }, [adaptersWithStandardAdapters, walletName]);\n const handleConnectError = useCallback(() => {\n if (adapter && adapter.name !== SolanaMobileWalletAdapterWalletName) {\n // If any error happens while connecting, unset the adapter.\n changeWallet(null);\n }\n }, [adapter, changeWallet]);\n const selectWallet = useCallback(\n (walletName: WalletName | null) => {\n hasUserSelectedAWallet.current = true;\n changeWallet(walletName);\n },\n [changeWallet]\n );\n return (\n \n {children}\n \n );\n}\n","import { type Dispatch, type SetStateAction, useEffect, useRef, useState } from 'react';\n\nexport function useLocalStorage(key: string, defaultState: T): [T, Dispatch>] {\n const state = useState(() => {\n try {\n const value = localStorage.getItem(key);\n if (value) return JSON.parse(value) as T;\n } catch (error: any) {\n if (typeof window !== 'undefined') {\n console.error(error);\n }\n }\n\n return defaultState;\n });\n const value = state[0];\n\n const isFirstRenderRef = useRef(true);\n useEffect(() => {\n if (isFirstRenderRef.current) {\n isFirstRenderRef.current = false;\n return;\n }\n try {\n if (value === null) {\n localStorage.removeItem(key);\n } else {\n localStorage.setItem(key, JSON.stringify(value));\n }\n } catch (error: any) {\n if (typeof window !== 'undefined') {\n console.error(error);\n }\n }\n }, [value, key]);\n\n return state;\n}\n","import type { Adapter } from '@solana/wallet-adapter-base';\nimport { WalletAdapterNetwork } from '@solana/wallet-adapter-base';\nimport {\n ConnectionProvider,\n WalletProvider,\n} from '@solana/wallet-adapter-react';\nimport { clusterApiUrl } from '@solana/web3.js';\nimport { type FC, type PropsWithChildren } from 'react';\n\nconst endpoint = clusterApiUrl(WalletAdapterNetwork.Mainnet);\n/**\n * Wallets that implement either of these standards will be available automatically.\n *\n * - Solana Mobile Stack Mobile Wallet Adapter Protocol\n * (https://github.com/solana-mobile/mobile-wallet-adapter)\n * - Solana Wallet Standard\n * (https://github.com/solana-labs/wallet-standard)\n *\n * If you wish to support a wallet that supports neither of those standards,\n * instantiate its legacy wallet adapter here. Common legacy adapters can be found\n * in the npm package `@solana/wallet-adapter-wallets`.\n */\nconst wallets: Adapter[] = [];\n\nexport const SVMBaseProvider: FC = ({ children }) => {\n return (\n \n \n {children}\n \n \n );\n};\n","import { ChainType } from '@lifi/sdk';\nimport { ConnectionContext } from '@solana/wallet-adapter-react';\nimport { useContext, type FC, type PropsWithChildren } from 'react';\nimport { isItemAllowed } from '../../utils/item.js';\nimport { useWidgetConfig } from '../WidgetProvider/WidgetProvider.js';\nimport { SVMBaseProvider } from './SVMBaseProvider.js';\nimport { SVMExternalContext } from './SVMExternalContext.js';\n\nexport function useInSolanaContext(): boolean {\n const { chains } = useWidgetConfig();\n const context = useContext(ConnectionContext);\n return (\n Boolean(context?.connection) && isItemAllowed(ChainType.SVM, chains?.types)\n );\n}\n\nexport const SVMProvider: FC = ({ children }) => {\n const inSolanaContext = useInSolanaContext();\n\n return inSolanaContext ? (\n \n {children}\n \n ) : (\n {children}\n );\n};\n","import { type FC, type PropsWithChildren } from 'react';\nimport { EVMProvider } from './EVMProvider.js';\nimport { SDKProviders } from './SDKProviders.js';\nimport { SVMProvider } from './SVMProvider.js';\n\nexport const WalletProvider: FC = ({ children }) => {\n return (\n \n \n \n {children}\n \n \n );\n};\n","import { createWithEqualityFn } from 'zustand/traditional';\n\nimport type {\n DefaultValues,\n FormFieldArray,\n FormFieldNames,\n FormValueControl,\n FormValues,\n FormValuesState,\n} from './types.js';\n\nexport const formDefaultValues: DefaultValues = {\n fromAmount: '',\n toAmount: '',\n tokenSearchFilter: '',\n};\n\nconst defaultValueToFormValue = (value: T): FormValueControl => ({\n isTouched: false,\n isDirty: false,\n value,\n});\n\nconst valuesToFormValues = (defaultValues: DefaultValues): FormValues => {\n return (Object.keys(defaultValues) as FormFieldNames[]).reduce(\n (accum, key) => ({\n ...accum,\n [key]: defaultValueToFormValue(defaultValues[key]),\n }),\n {} as FormValues,\n );\n};\n\nconst isString = (str: any) => typeof str === 'string' || str instanceof String;\n\nconst getUpdatedTouchedFields = (userValues: FormValues) => {\n return (Object.keys(userValues) as FormFieldNames[]).reduce(\n (accum, key) => {\n if (userValues[key]?.isTouched) {\n accum[key] = true;\n }\n return accum;\n },\n {} as Record,\n );\n};\n\nconst mergeDefaultFormValues = (\n userValues: FormValues,\n defaultValues: FormValues,\n) =>\n (Object.keys(defaultValues) as FormFieldNames[]).reduce(\n (accum, key) => {\n const formValue = {\n isTouched: !!(\n userValues[key]?.isTouched || defaultValues[key]?.isTouched\n ),\n isDirty: !!(userValues[key]?.isDirty || defaultValues[key]?.isTouched),\n value:\n userValues[key]?.value || Number.isFinite(userValues[key]?.value)\n ? userValues[key]?.value\n : defaultValues[key]?.value,\n };\n\n return {\n ...accum,\n [key]: formValue,\n };\n },\n { ...valuesToFormValues(formDefaultValues) },\n );\n\nexport const createFormStore = (defaultValues?: DefaultValues) =>\n createWithEqualityFn((set, get) => {\n const _defaultValues = valuesToFormValues({\n ...formDefaultValues,\n ...defaultValues,\n });\n return {\n defaultValues: _defaultValues,\n userValues: _defaultValues,\n touchedFields: {},\n isValid: true,\n isValidating: false,\n errors: {},\n validation: {},\n setDefaultValues: (defaultValue) => {\n const defaultFormValues = valuesToFormValues(defaultValue);\n set((state) => ({\n defaultValues: defaultFormValues,\n userValues: mergeDefaultFormValues(\n state.userValues,\n defaultFormValues,\n ),\n }));\n },\n setUserAndDefaultValues: (formValues) => {\n const currentUserValues = get().userValues;\n (Object.keys(formValues) as FormFieldNames[]).forEach((key) => {\n if (formValues[key] !== currentUserValues[key]?.value) {\n get().resetField(key, { defaultValue: formValues[key] });\n get().setFieldValue(key, formValues[key], { isTouched: true });\n }\n });\n },\n isTouched: (fieldName: FormFieldNames) =>\n !!get().userValues[fieldName]?.isTouched,\n setAsTouched: (fieldName: FormFieldNames) => {\n const userValues = {\n ...get().userValues,\n [fieldName]: {\n ...get().userValues[fieldName],\n isTouched: true,\n },\n };\n\n const touchedFields = getUpdatedTouchedFields(userValues);\n\n set(() => ({\n userValues,\n touchedFields,\n }));\n },\n resetField: (fieldName, { defaultValue } = {}) => {\n if (defaultValue) {\n const fieldValues = {\n ...get().defaultValues[fieldName],\n value: defaultValue,\n };\n const defaultValues = {\n ...get().defaultValues,\n [fieldName]: { ...fieldValues },\n };\n const userValues = {\n ...get().userValues,\n [fieldName]: { ...fieldValues },\n };\n const touchedFields = getUpdatedTouchedFields(userValues);\n\n set(() => {\n return {\n defaultValues,\n userValues,\n touchedFields,\n };\n });\n } else {\n const userValues = {\n ...get().userValues,\n [fieldName]: { ...get().defaultValues[fieldName] },\n };\n const touchedFields = getUpdatedTouchedFields(userValues);\n\n set(() => ({\n userValues,\n touchedFields,\n }));\n }\n },\n setFieldValue: (fieldName, value, { isDirty, isTouched } = {}) => {\n const userValues = {\n ...get().userValues,\n [fieldName]: {\n value,\n isDirty:\n isDirty === undefined\n ? get().userValues[fieldName]?.isDirty\n : isDirty,\n isTouched:\n isTouched === undefined\n ? get().userValues[fieldName]?.isTouched\n : isTouched,\n },\n };\n\n const touchedFields = getUpdatedTouchedFields(userValues);\n\n set(() => ({\n userValues,\n touchedFields,\n }));\n },\n getFieldValues: (...names: T) =>\n names.map((name) => get().userValues[name]?.value) as FormFieldArray,\n addFieldValidation: (name, validationFn) => {\n set((state) => ({\n validation: {\n ...state.validation,\n [name]: validationFn,\n },\n }));\n },\n triggerFieldValidation: async (name) => {\n try {\n let valid = true;\n set(() => ({ isValid: false, isValidating: true }));\n\n const validationFn = get().validation[name];\n\n if (validationFn) {\n const result = await validationFn(get().userValues?.[name]?.value);\n if (isString(result)) {\n valid = false;\n set((state) => ({\n errors: {\n ...state.errors,\n [name]: result,\n },\n }));\n } else {\n valid = result as boolean;\n if (valid) {\n get().clearErrors(name);\n }\n }\n }\n\n set(() => ({ isValid: valid, isValidating: false }));\n return valid;\n } catch (err) {\n set(() => ({ isValidating: false }));\n throw err;\n }\n },\n clearErrors: (name) => {\n const newErrors = { ...get().errors };\n\n delete newErrors[name];\n\n set(() => ({\n errors: newErrors,\n }));\n },\n };\n }, Object.is);\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { useEffect } from 'react';\nimport { useAccount } from '../../hooks/useAccount.js';\nimport { useChains } from '../../hooks/useChains.js';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { formDefaultValues } from '../../stores/form/createFormStore.js';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport type { DefaultValues } from './types.js';\nimport { useFieldActions } from './useFieldActions.js';\n\nexport const FormUpdater: React.FC<{\n reactiveFormValues: Partial;\n}> = ({ reactiveFormValues }) => {\n const { fromChain, toChain, toAddress } = useWidgetConfig();\n const { account } = useAccount();\n const { chains } = useChains();\n const { setSendToWallet } = useSendToWalletActions();\n const { setSelectedBookmark } = useBookmarkActions();\n\n const {\n isTouched,\n resetField,\n setFieldValue,\n getFieldValues,\n setUserAndDefaultValues,\n } = useFieldActions();\n // Set wallet chain as default if no chains are provided by config and if they were not changed during widget usage\n useEffect(() => {\n const chainAllowed =\n account.chainId && chains?.some((chain) => chain.id === account.chainId);\n\n if (!account.isConnected || !account.chainId || !chainAllowed) {\n return;\n }\n\n if (!fromChain && !isTouched('fromChain') && !isTouched('fromToken')) {\n resetField('fromChain', { defaultValue: account.chainId });\n setFieldValue('fromToken', '');\n if (isTouched('fromAmount')) {\n setFieldValue('fromAmount', '');\n }\n }\n if (!toChain && !isTouched('toChain') && !isTouched('toToken')) {\n resetField('toChain', { defaultValue: account.chainId });\n setFieldValue('toToken', '');\n }\n }, [\n account.chainId,\n account.isConnected,\n chains,\n fromChain,\n toChain,\n isTouched,\n resetField,\n setFieldValue,\n ]);\n\n // Makes widget config options reactive to changes\n // should update userValues when defaultValues updates and includes additional logic for chains\n useEffect(() => {\n if (reactiveFormValues.toAddress) {\n setSendToWallet(true);\n }\n\n setSelectedBookmark(toAddress);\n\n setUserAndDefaultValues(\n accountForChainId(reactiveFormValues, account.chainId),\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n toAddress,\n reactiveFormValues,\n getFieldValues,\n resetField,\n setFieldValue,\n setUserAndDefaultValues,\n setSendToWallet,\n setSelectedBookmark,\n ]);\n\n return null;\n};\n\nconst accountForChainId = (\n defaultValues: Partial,\n chainId?: number,\n) => {\n const result: Partial = { ...defaultValues };\n for (const key in result) {\n const k = key as keyof DefaultValues;\n if (result[k] === formDefaultValues[k]) {\n if ((k === 'fromChain' || k === 'toChain') && chainId) {\n result[k] = chainId;\n }\n }\n }\n return result;\n};\n","import type { PropsWithChildren } from 'react';\nimport { useMemo, useRef } from 'react';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport type { FormRef, ToAddress } from '../../types/widget.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport { FormStoreContext } from './FormStoreContext.js';\nimport { FormUpdater } from './FormUpdater.js';\nimport { createFormStore, formDefaultValues } from './createFormStore.js';\nimport type { DefaultValues, FormStoreStore } from './types.js';\nimport { useFormRef } from './useFormRef.js';\n\n// decorates and initialise the form date for use in the form store\nconst initialiseDefaultValues = (\n defaultValues: Partial,\n fromAmount?: number | string,\n toAmount?: number | string,\n toAddress?: ToAddress,\n hiddenToAddress?: boolean,\n) => ({\n ...formDefaultValues,\n ...defaultValues,\n fromAmount:\n (typeof fromAmount === 'number' ? fromAmount?.toPrecision() : fromAmount) ||\n formDefaultValues.fromAmount,\n toAmount:\n (typeof toAmount === 'number' ? toAmount?.toPrecision() : toAmount) ||\n formDefaultValues.toAmount,\n // Prevent setting address when the field is hidden\n toAddress: hiddenToAddress\n ? formDefaultValues.toAddress\n : toAddress?.address || formDefaultValues.toAddress,\n});\n\ninterface FormStoreProviderProps extends PropsWithChildren {\n formRef?: FormRef;\n}\n\nexport const FormStoreProvider: React.FC = ({\n children,\n formRef,\n}) => {\n const widgetConfig = useWidgetConfig();\n\n const {\n fromChain,\n fromToken,\n toChain,\n toToken,\n fromAmount,\n toAmount,\n toAddress,\n hiddenUI,\n formUpdateKey,\n } = widgetConfig;\n\n const storeRef = useRef();\n\n const hiddenToAddress = hiddenUI?.includes(HiddenUI.ToAddress);\n\n const configHasFromChain = widgetConfig.hasOwnProperty('fromChain');\n const configHasFromToken = widgetConfig.hasOwnProperty('fromToken');\n const configHasFromAmount = widgetConfig.hasOwnProperty('fromAmount');\n const configHasToAmount = widgetConfig.hasOwnProperty('toAmount');\n const configHasToAddress = widgetConfig.hasOwnProperty('toAddress');\n const configHasToChain = widgetConfig.hasOwnProperty('toChain');\n const configHasToToken = widgetConfig.hasOwnProperty('toToken');\n\n // We use the presence/absence of a property to decide if the form values in state need to be updated\n // We only build and set a property on the memoized form values here if they are included in the\n // config - undefined is considered a valid value that will reset that form field\n const reactiveFormValues = useMemo(\n () => ({\n ...(configHasFromChain ? { fromChain } : undefined),\n ...(configHasFromToken ? { fromToken } : undefined),\n ...(configHasFromAmount\n ? {\n fromAmount:\n (typeof fromAmount === 'number'\n ? fromAmount?.toPrecision()\n : fromAmount) || formDefaultValues.fromAmount,\n }\n : undefined),\n ...(configHasFromAmount\n ? {\n toAmount:\n (typeof toAmount === 'number'\n ? toAmount?.toPrecision()\n : toAmount) || formDefaultValues.toAmount,\n }\n : undefined),\n ...(configHasToChain ? { toChain } : undefined),\n ...(configHasToToken ? { toToken } : undefined),\n ...(configHasToAddress\n ? {\n toAddress: hiddenToAddress\n ? formDefaultValues.toAddress\n : toAddress?.address || formDefaultValues.toAddress,\n }\n : undefined),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n fromAmount,\n toAmount,\n fromChain,\n fromToken,\n hiddenToAddress,\n toAddress,\n toChain,\n toToken,\n // formUpdateKey should be a randomly assigned unique key. It can be used to force updates for the form field values\n formUpdateKey,\n configHasFromChain,\n configHasFromToken,\n configHasFromAmount,\n configHasToAmount,\n configHasToAddress,\n configHasToChain,\n configHasToToken,\n ],\n );\n\n if (!storeRef.current) {\n storeRef.current = createFormStore(\n initialiseDefaultValues(\n reactiveFormValues,\n fromAmount,\n toAmount,\n toAddress,\n hiddenToAddress,\n ),\n );\n }\n\n useFormRef(storeRef.current, formRef);\n\n return (\n \n {children}\n \n \n );\n};\n","import { useImperativeHandle } from 'react';\nimport { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';\nimport { useBookmarkActions } from '../../stores/bookmarks/useBookmarkActions.js';\nimport { formDefaultValues } from '../../stores/form/createFormStore.js';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport type { FormRef } from '../../types/widget.js';\nimport { HiddenUI } from '../../types/widget.js';\nimport type { FormStoreStore, GenericFormValue } from './types.js';\n\nexport const useFormRef = (formStore: FormStoreStore, formRef?: FormRef) => {\n const { setSendToWallet } = useSendToWalletActions();\n const { setSelectedBookmark } = useBookmarkActions();\n const { hiddenUI } = useWidgetConfig();\n\n useImperativeHandle(formRef, () => {\n const sanitizeValue: {\n [key: string]: (value: any) => GenericFormValue;\n } = {\n fromAmount: (value) =>\n (typeof value === 'number' ? value?.toPrecision() : value) ||\n formDefaultValues.fromAmount,\n toAmount: (value) =>\n (typeof value === 'number' ? value?.toPrecision() : value) ||\n formDefaultValues.toAmount,\n toAddress: (value) => {\n if (hiddenUI?.includes(HiddenUI.ToAddress)) {\n return formDefaultValues.toAddress;\n }\n\n const isToAddressObj = typeof value !== 'string';\n\n const address =\n (isToAddressObj ? value?.address : value) ||\n formDefaultValues.toAddress;\n\n // sets the send to wallet button state to be open\n // if there is an address to display\n if (address) {\n setSendToWallet(address);\n }\n\n // we can assume that the toAddress has been passed as ToAddress object\n // and display it accordingly - this ensures that if a name is included\n // that it is displayed in the Send To Wallet form field correctly\n if (isToAddressObj) {\n setSelectedBookmark(value);\n }\n\n return address;\n },\n };\n\n return {\n setFieldValue: (fieldName, value, options) => {\n const sanitizedValue = (\n sanitizeValue[fieldName] ? sanitizeValue[fieldName](value) : value\n ) as GenericFormValue;\n\n const fieldValueOptions = options?.setUrlSearchParam\n ? { isTouched: options?.setUrlSearchParam }\n : undefined;\n\n formStore\n .getState()\n .setFieldValue(fieldName, sanitizedValue, fieldValueOptions);\n },\n };\n }, [formStore, hiddenUI, setSendToWallet, setSelectedBookmark]);\n};\n","import type { PropsWithChildren } from 'react';\nimport type { WidgetConfigProps } from '../types/widget.js';\nimport { BookmarkStoreProvider } from './bookmarks/BookmarkStore.js';\nimport { ChainOrderStoreProvider } from './chains/ChainOrderStore.js';\nimport { FormStoreProvider } from './form/FormStore.js';\nimport { HeaderStoreProvider } from './header/useHeaderStore.js';\nimport { RouteExecutionStoreProvider } from './routes/RouteExecutionStore.js';\nimport { SplitSubvariantStoreProvider } from './settings/useSplitSubvariantStore.js';\n\nexport const StoreProvider: React.FC> = ({\n children,\n config,\n formRef,\n}) => {\n return (\n \n \n \n \n \n \n {children}\n \n \n \n \n \n \n );\n};\n","import { useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { useSendToWalletActions } from '../../stores/settings/useSendToWalletStore.js';\nimport { formatInputAmount } from '../../utils/format.js';\nimport type { DefaultValues, FormFieldNames } from '../form/types.js';\nimport { useFieldActions } from '../form/useFieldActions.js';\nimport { useFieldValues } from '../form/useFieldValues.js';\nimport { useTouchedFields } from '../form/useTouchedFields.js';\n\nconst formValueKeys: FormFieldNames[] = [\n 'fromAmount',\n 'fromChain',\n 'fromToken',\n 'toAddress',\n 'toChain',\n 'toToken',\n];\n\nconst getDefaultValuesFromQueryString = (): Partial => {\n const searchParams = Object.fromEntries(\n new URLSearchParams(window?.location.search),\n );\n\n // Prevent using fromToken/toToken params if chain is not selected\n ['from', 'to'].forEach((key) => {\n if (searchParams[`${key}Token`] && !searchParams[`${key}Chain`]) {\n delete searchParams[`${key}Token`];\n }\n });\n\n return {\n ...(Number.isFinite(parseInt(searchParams.fromChain, 10))\n ? { fromChain: parseInt(searchParams.fromChain, 10) }\n : {}),\n ...(Number.isFinite(parseInt(searchParams.toChain, 10))\n ? { toChain: parseInt(searchParams.toChain, 10) }\n : {}),\n ...(searchParams.fromToken ? { fromToken: searchParams.fromToken } : {}),\n ...(searchParams.toToken ? { toToken: searchParams.toToken } : {}),\n ...(Number.isFinite(parseFloat(searchParams.fromAmount))\n ? { fromAmount: formatInputAmount(searchParams.fromAmount) }\n : {}),\n ...(searchParams.toAddress ? { toAddress: searchParams.toAddress } : {}),\n };\n};\n\nexport const URLSearchParamsBuilder = () => {\n const { pathname } = useLocation();\n const touchedFields = useTouchedFields();\n const values = useFieldValues(...formValueKeys);\n const { setSendToWallet } = useSendToWalletActions();\n\n // Using these methods as trying to use the touchedFields and values above\n // often has a lag that can effect the widgets initialisation sequence\n // and accidentally cause values to be wiped from the query string\n const { getFieldValues, isTouched, setUserAndDefaultValues } =\n useFieldActions();\n\n useEffect(() => {\n // get the initial values from the querysting\n const formValues = getDefaultValuesFromQueryString();\n\n if (formValues.toAddress) {\n setSendToWallet(true);\n }\n\n setUserAndDefaultValues(formValues);\n }, [setUserAndDefaultValues, setSendToWallet]);\n\n useEffect(() => {\n // set the values on the querysting\n const url = new URL(window.location as any);\n formValueKeys.forEach((key, index) => {\n const value = getFieldValues(key)[0];\n if (isTouched(key) && value) {\n url.searchParams.set(key, value.toString());\n } else if (url.searchParams.has(key) && !value) {\n url.searchParams.delete(key);\n }\n });\n url.searchParams.sort();\n window.history.replaceState(window.history.state, '', url);\n }, [pathname, touchedFields, values, isTouched, getFieldValues]);\n\n return null;\n};\n","import { shallow } from 'zustand/shallow';\nimport { useFormStore } from './useFormStore.js';\n\nexport const useTouchedFields = () => {\n const touchedFields = useFormStore((store) => store.touchedFields, shallow);\n\n return touchedFields;\n};\n","import { QueryClientProvider } from '@tanstack/react-query';\nimport type { PropsWithChildren } from 'react';\nimport { Fragment } from 'react';\nimport { MemoryRouter, useInRouterContext } from 'react-router-dom';\nimport { PageEntered } from './components/PageEntered.js';\nimport { queryClient } from './config/queryClient.js';\nimport { I18nProvider } from './providers/I18nProvider/I18nProvider.js';\nimport { ThemeProvider } from './providers/ThemeProvider/ThemeProvider.js';\nimport { WalletProvider } from './providers/WalletProvider/WalletProvider.js';\nimport {\n WidgetProvider,\n useWidgetConfig,\n} from './providers/WidgetProvider/WidgetProvider.js';\nimport { StoreProvider } from './stores/StoreProvider.js';\nimport { URLSearchParamsBuilder } from './stores/form/URLSearchParamsBuilder.js';\nimport type { WidgetConfigProps } from './types/widget.js';\n\nexport const AppProvider: React.FC> = ({\n children,\n config,\n formRef,\n}) => {\n return (\n \n \n \n \n \n \n {children}\n \n \n \n \n \n \n );\n};\n\nexport const AppRouter: React.FC> = ({ children }) => {\n const { buildUrl } = useWidgetConfig();\n const inRouterContext = useInRouterContext();\n const Router = inRouterContext ? Fragment : MemoryRouter;\n return (\n \n {children}\n {buildUrl ? : null}\n \n \n );\n};\n","'use client';\nimport { forwardRef, useMemo } from 'react';\nimport { AppDefault } from './AppDefault.js';\nimport type { WidgetDrawer } from './AppDrawer.js';\nimport { AppDrawer } from './AppDrawer.js';\nimport { AppProvider } from './AppProvider.js';\nimport type { WidgetConfig, WidgetProps } from './types/widget.js';\n\nexport const App = forwardRef(\n ({ elementRef, open, onClose, integrator, formRef, ...other }, ref) => {\n const config: WidgetConfig = useMemo(() => {\n const config = { integrator, ...other, ...other.config };\n if (config.variant === 'drawer') {\n config.theme = {\n ...config.theme,\n container: {\n height: '100%',\n ...config.theme?.container,\n },\n };\n }\n return config;\n }, [integrator, other]);\n\n if (config.variant === 'drawer') {\n return (\n \n \n \n \n \n );\n }\n\n return (\n \n \n \n );\n },\n);\n","// eslint-disable-next-line import/named\nimport { LiFiWidget } from '@lifi/widget';\nimport { styled, useTheme } from 'styled-components';\nimport { useChainId } from 'wagmi';\n\nimport { Networks, networks } from '../data/networks';\nimport useWindowProps from '../hooks/useWindowProps';\n\nimport './Swapper.css';\n\nconst HalfSection = styled.div`\n display: flex;\n width: 50%;\n\n @media (orientation: portrait) and (max-width: 900px) {\n margin-right: 0;\n width: 90%;\n }\n\n @media (orientation: portrait) and (max-width: 700px) {\n width: 100%;\n margin-bottom: var(--space-2xl);\n }\n\n @media (min-width: 1900px) {\n width: 35%;\n }\n`;\n\nconst usdcMapper: Record = {\n [1]: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n [10]: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n [137]: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n [8453]: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n [42161]: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n [324]: '0x1d17CBcF0D6D143135aE902365D2E5e2A16538D4',\n};\n\nconst Swapper = () => {\n const { colors } = useTheme();\n const chainId = useChainId();\n const { width } = useWindowProps();\n\n const getWidgetWidth = (): string => {\n if (width > 1900) {\n return `calc((${width}px - 2 * var(--space-2xl)) * 0.35)`;\n }\n\n if (width < 900 && width > 739) {\n return `calc((${width}px - 2 * var(--space-2xl)) * 0.5)`;\n }\n\n if (width <= 739 && width > 700) {\n return `calc((${width}px - 2 * var(--space-2xl)) * 0.9)`;\n }\n\n if (width <= 700) {\n return `calc((${width}px - 2 * var(--space-2xl)) * 1)`;\n }\n\n return `calc((${width}px - 2 * var(--space-2xl)) * 0.5)`;\n };\n\n const currentNetwork = Object.keys(networks).find((key) => parseInt(networks[key].chainId) === chainId) as Networks | undefined;\n\n return (\n <>\n \n ([\n {\n symbol: 'USDM',\n decimals: 18,\n name: 'USDM',\n chainId: parseInt(network.chainId, 16),\n address: network.usdm.address,\n },\n ...(network.wusdm.enabled ? [{\n symbol: 'WUSDM',\n decimals: 18,\n name: 'wUSDM',\n chainId: parseInt(network.chainId, 16),\n address: network.wusdm.address,\n }] : []),\n ])).reduce((acc, curr) => [...acc, ...curr], []),\n }}\n chains={{\n allow: Object.values(networks).filter(network => network.swap.enabled).map((network) => parseInt(network.chainId, 16)),\n }}\n hiddenUI={['appearance', 'language']}\n appearance=\"light\"\n theme={{\n container: {\n border: `1px solid ${colors.grayLight}`,\n borderRadius: 'var(--space-2xs)',\n maxHeight: 820,\n width: getWidgetWidth(),\n maxWidth: getWidgetWidth(),\n minWidth: 'auto',\n },\n palette: {\n primary: { main: colors.brand },\n secondary: { main: colors.grayLight },\n },\n }}\n />\n \n \n );\n};\n\nexport default Swapper;\n","import { networks } from './networks';\n\nconst availableUsdmNetworks = Object.values(networks);\nconst availableWusdmNetworks = Object.values(networks).filter((network) => network.wusdm.enabled);\n\nexport const buyFaqs = [\n {\n question: 'How does it work?',\n answer:\n \"It's simple. You choose your source token, input the amount of USDM/wUSDM you want to buy, and the app will show you the best possible quote, as sourced from the matching partners. You can then proceed to buy USDM/wUSDM at the price reflected and get the best execution available by the partner you select.\",\n },\n {\n question: 'In which chains can I buy USDM/wUSDM?',\n answer:\n `USDM is currently live on ${availableUsdmNetworks\n .map((network) => network.chainName)\n .slice(0, -1)\n .join(', ')}, and ${availableUsdmNetworks.slice(-1)[0].chainName}.\\n\\n\n wUSDM is currently live on ${availableWusdmNetworks\n .map((network) => network.chainName)\n .slice(0, -1)\n .join(', ')}, and ${availableWusdmNetworks.slice(-1)[0].chainName}. \n `,\n },\n {\n question: 'Am I getting the best possible quote?',\n answer:\n \"LiFi, the integration partner, analyzes all aggregators and strives to get the best possible quote available to them. This doesn't guarantee the best quote since some aggregators might not be available at the time.\",\n },\n {\n question: 'Are there any fees associated with buying USDM/wUSDM?',\n answer: 'Mountain Protocol does not charge fees to buy USDM/wUSDM as it performs no function other than displaying protocols that offer those utilities. The network fees, charged in gas, will be displayed in your wallet. LiFi fees will be displayed on the pre-confirmation screen.',\n },\n {\n question: 'Is there any other way to get USDM?',\n answer: 'Yes. If you are an institutional prospect, feel free to contact us and our team can help you onboard to Mountain Protocol\\'s platform.',\n },\n {\n question: 'Is Mountain Protocol acting as an exchange?',\n answer: 'No, Mountain Protocol is simply enabling a front-end to LiFi, a liquidity aggregator, in order to make it easier for users to buy/sell at the best price available.',\n },\n];\n","import { styled } from 'styled-components';\n\nimport Title from '../components/Title';\nimport Subtitle from '../components/Subtitle';\nimport FAQs from '../components/FAQs';\nimport Swapper from '../sections/Swapper';\nimport { buyFaqs } from '../data/buyFaqs';\nimport usePageViewSend from '../hooks/usePageViewSend';\nimport Head from '../components/Head';\n\nconst Wrapper = styled.div`\n width: 100%;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n`;\n\nconst BuyScreen = () => {\n usePageViewSend();\n \n return (\n \n \n \n <Subtitle text=\"Swap anything to and from USDM/wUSDM.\" />\n <Swapper />\n <FAQs faqs={buyFaqs} />\n </Wrapper>\n );\n};\n\nexport default BuyScreen;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ArrowRight\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNSAxMmgxNCIgLz4KICA8cGF0aCBkPSJtMTIgNSA3IDctNyA3IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/arrow-right\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst ArrowRight = createLucideIcon('ArrowRight', [\n ['path', { d: 'M5 12h14', key: '1ays0h' }],\n ['path', { d: 'm12 5 7 7-7 7', key: 'xquz4c' }],\n]);\n\nexport default ArrowRight;\n","var _path, _path2;\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nimport * as React from \"react\";\nfunction SvgMountain(_ref, svgRef) {\n let {\n title,\n titleId,\n ...props\n } = _ref;\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n width: 160,\n height: 160,\n viewBox: \"0 0 160 160\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, _path || (_path = /*#__PURE__*/React.createElement(\"path\", {\n d: \"M80.029 105.82C94.2722 105.82 105.82 94.273 105.82 80.0292C105.82 65.7854 94.2722 54.2385 80.029 54.2385C65.7857 54.2385 54.2383 65.7854 54.2383 80.0292C54.2383 94.273 65.7857 105.82 80.029 105.82Z\",\n fill: \"white\"\n })), _path2 || (_path2 = /*#__PURE__*/React.createElement(\"path\", {\n fillRule: \"evenodd\",\n clipRule: \"evenodd\",\n d: \"M99.6369 4.56773C94.3015 8.99093 87.4498 11.6496 79.9786 11.6496C72.5436 11.6496 65.7242 9.01763 60.3999 4.63422C54.7511 -0.0156612 45.6891 -1.99479 40.4695 3.13111C27.9137 15.4603 15.4606 27.9138 3.1305 40.4697C-1.99439 45.6893 -0.0157614 54.7518 4.63461 60.3995C9.01701 65.7239 11.6495 72.5438 11.6495 79.9783C11.6495 87.4506 8.99082 94.3017 4.56812 99.6377C-0.101394 105.27 -2.10924 114.325 3.01162 119.55C15.3297 132.117 27.814 144.539 40.3748 156.865C45.6115 162.004 54.7178 160.008 60.3787 155.34C65.7061 150.947 72.5335 148.308 79.9786 148.308C87.4599 148.308 94.3196 150.973 99.6591 155.406C105.304 160.095 114.402 162.12 119.644 156.985C132.215 144.672 144.672 132.216 156.985 119.645C162.12 114.402 160.095 105.304 155.406 99.6593C150.972 94.3203 148.307 87.4606 148.307 79.9783C148.307 72.5338 150.946 65.7058 155.34 60.3784C160.008 54.7175 162.004 45.6122 156.865 40.375C144.54 27.8141 132.117 15.3293 119.549 3.01172C114.324 -2.10964 105.27 -0.100791 99.6369 4.56773ZM65.5177 27.0001C73.543 18.9748 86.5542 18.9748 94.5795 27.0001L133.173 65.5934C141.198 73.6188 141.198 86.63 133.173 94.6553L94.5795 133.249C86.5542 141.274 73.543 141.274 65.5177 133.249L26.9244 94.6553C18.8991 86.63 18.8991 73.6188 26.9244 65.5934L65.5177 27.0001Z\",\n fill: \"white\"\n })));\n}\nconst ForwardRef = /*#__PURE__*/React.forwardRef(SvgMountain);\nexport default __webpack_public_path__ + \"static/media/mountain.c92f3b3dbc3eea06fa2f84ca10d81f31.svg\";\nexport { ForwardRef as ReactComponent };","import { useNavigate } from 'react-router-dom';\nimport { ArrowRight } from 'lucide-react';\nimport { styled } from 'styled-components';\n\nimport LogoImg from '../assets/mountain.svg';\nimport Button from '../components/Button';\nimport Head from '../components/Head';\n\nconst Wrapper = styled.div`\n width: 50%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n\n @media (orientation: portrait) and (max-width: 900px) {\n width: 90%;\n }\n\n @media (orientation: portrait) and (max-width: 700px) {\n width: 100%;\n margin-bottom: var(--space-2xl);\n }\n\n @media (min-width: 1900px) {\n width: 35%;\n }\n`;\n\nconst Logo = styled.img`\n width: 30%;\n margin-bottom: var(--space-xl);\n\n @media (orientation: portrait) and (max-width: 900px) {\n width: 25%;\n margin-bottom: var(--space-2xl);\n }\n\n @media (orientation: portrait) and (max-width: 700px) {\n width: 35%;\n margin-bottom: var(--space-4xl);\n }\n`;\n\nconst Title = styled.h2`\n font-weight: var(--font-weight-light);\n font-size: var(--font-size-3);\n color: ${({ theme }) => theme.colors.background};\n margin: 0;\n margin-bottom: var(--space-s);\n text-align: center;\n\n @media (orientation: portrait) and (max-width: 900px) {\n font-size: var(--font-size-4);\n margin-bottom: var(--space-m);\n }\n\n @media (orientation: portrait) and (max-width: 700px) {\n font-size: var(--font-size-6);\n margin-bottom: var(--space-l);\n }\n`;\n\nconst Body = styled.p`\n font-size: var(--font-size-0);\n line-height: 1.5;\n margin: 0;\n color: ${({ theme }) => theme.colors.background};\n font-weight: var(--font-weight-light);\n text-align: center;\n margin-bottom: var(--space-xl);\n\n @media (orientation: portrait) and (max-width: 900px) {\n font-size: var(--font-size-2);\n margin-bottom: var(--space-2xl);\n }\n\n @media (orientation: portrait) and (max-width: 700px) {\n font-size: var(--font-size-3);\n margin-bottom: var(--space-4xl);\n }\n`;\n\nconst ButtonWrapper = styled.div`\n width: 70%;\n`;\n\nconst NotFoundScreen = () => {\n const navigate = useNavigate();\n\n const goBackHome = () => navigate('/buy');\n\n return (\n <Wrapper>\n <Head\n title=\"Page not found - Mountain Protocol USDM\"\n description=\"We couldn't find the page you are looking for\"\n keywords=\"not found, page not found\"\n />\n <Logo src={LogoImg} alt=\"Mountain Protocol Logo\" />\n <Title>We couldn't find the page you are looking for\n Apologies for the inconvenience, the page you are looking for doesn't exist. Please, make sure the URL is correct.\n \n \n \n \n );\n};\n\nexport default NotFoundScreen;\n","import { createBrowserRouter } from 'react-router-dom';\n\nimport WrapScreen from './screens/WrapScreen';\nimport LiquidityScreen from './screens/LiquidityScreen';\nimport BridgeScreen from './screens/BridgeScreen';\nimport SwapScreen from './screens/BuyScreen';\nimport NotFoundScreen from './screens/NotFoundScreen';\n\nconst router = createBrowserRouter([\n {\n path: '/wrap',\n element: ,\n },\n {\n path: '/buy',\n element: ,\n },\n {\n path: '/liquidity',\n element: ,\n },\n {\n path: '/bridge',\n element: ,\n },\n {\n path: '/',\n element: ,\n },\n {\n path: '*',\n element: ,\n },\n]);\n\nexport default router;\n","import { styled } from 'styled-components';\n\nimport './Footer.css';\nimport useInternalUseStore from '../state/useInternalUseStore';\n\nconst FooterWrapper = styled.footer`\n border-top: 1px solid ${({ theme }) => theme.colors.grayDark};\n margin-top: var(--space-2xl);\n padding: 0 var(--space-2xl);\n width: calc(100% - 2 * var(--space-2xl));\n\n @media (orientation: portrait) and (max-width: 900px) {\n margin-top: var(--space-4xl);\n }\n`;\n\nconst year = (new Date()).getFullYear();\n\nconst Footer = () => {\n const { internalUse, setInternalUse } = useInternalUseStore();\n\n return (\n \n \n
\n
\n
\n {\n setInternalUse(!internalUse);\n }}\n >\n \n \n \n
{`Copyright © ${year} Mountain Protocol. All rights reserved.`}
\n
\n Terms of Use & Privacy Policy\n
\n
\n );\n};\n\nexport default Footer;\n","// eslint-disable-next-line import/no-named-as-default\nimport styled, { ThemeProvider, createGlobalStyle } from 'styled-components';\nimport './styles/index.css';\nimport { ToastContainer } from 'react-toastify';\n// eslint-disable-next-line import/no-unresolved\nimport { createWeb3Modal } from '@web3modal/wagmi/react';\nimport { RouterProvider } from 'react-router-dom';\nimport { WagmiProvider } from 'wagmi';\nimport { arbitrum, base, mainnet, optimism, polygon, zksync, celo } from 'wagmi/chains';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { defaultWagmiConfig } from '@web3modal/wagmi';\n\nimport theme from './theme';\nimport Topbar from './sections/Topbar';\nimport 'react-toastify/dist/ReactToastify.min.css';\nimport router from './router';\nimport Footer from './sections/Footer';\n\ndeclare module 'styled-components' {\n export interface DefaultTheme {\n colors: { [index: string]: string };\n }\n}\n\nconst GlobalStyle = createGlobalStyle`\n html {\n display: flex;\n flex-direction: column;\n align-items: center;\n overflow: visible;\n font-size: min(1vw, 15px);\n background-color: ${theme.colors.background};\n background-color: #000000;\n }\n \n body {\n font-family: 'SF Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,\n Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;\n padding: 0;\n margin: auto;\n width: 100%;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n overflow: visible;\n }\n\n #root {\n width: 100%;\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n }\n`;\n\nconst Wrapper = styled.div`\n width: 100%;\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n`;\n\nconst RouterWrapper = styled.div`\n padding: 0 var(--space-2xl);\n width: calc(100% - 2 * var(--space-2xl));\n display: flex;\n flex-direction: column;\n justify-content: flex-start;\n align-items: center;\n`;\n\nconst metadata = {\n name: 'DeFi - Mountain Protocol USDM',\n description: \"Mountain Protocol's USDM Official DeFi App\",\n url: 'https://defi.mountainprotocol.com',\n icons: [\n 'https://security.mountainprotocol.com/_ipx/w_96,q_75/%2Fmountain.png?q=75&url=%2Fmountain.png&w=96',\n ],\n};\n\nconst chains = [mainnet, arbitrum, polygon, optimism, base, zksync, celo] as const;\nconst config = defaultWagmiConfig({\n chains,\n projectId: process.env.REACT_APP_PROJECT_ID || '',\n metadata,\n});\n\ncreateWeb3Modal({\n metadata,\n wagmiConfig: config,\n projectId: process.env.REACT_APP_PROJECT_ID || '',\n enableAnalytics: true,\n});\n\nconst queryClient = new QueryClient();\n\nconst App = () => {\n return (\n \n \n \n \n \n \n \n \n \n \n